1

angular.module('myModule', ['somedeps'])
  .directive('myAwesomeDirective', myAwesomeDirectiveFn)


function myAwesomeDirectiveFn() {
  function myAwesomeDirectiveCtrl (someDeps) {
    var vm = this;
    vm.variable_x, vm.variable_y;
    
    vm.action_a = function action_a() {
      console.log("Yaaa, I am action a");
    }
  },
    
  function myAwesomeLinker(scope, element, attribute, controller) {
    //Just print something on console
    element.on('click', function () {
      controller.action_a();
    });
  }
  
  return {
    restrict : 'AE',
    scope : {
      x : '=',
      y : '='
    },
    controller : myAwesomeDirectiveCtrl,
    controllerAs : 'vm',
    link : myAwesomeLinker,
    templateUrl : 'someTemplate.html'
  }
}

Now I want to write a unit test to test my directive and controller inside it.

I get the directive by doing following

directiveElement = angular.element('<my-awesome-directive x = "x" y = "y" />');
var vm = $rootScope.$new();
vm.x = 10;
vm.y = 20;

directiveElement = $compile(directiveElement)(vm);
vm.$digest();

My understanding was that I can get the controller by doing following

controller = directiveElement.controller('myAwesomeDirective');

but controlller is still undefined.

What am I doing wrong or is this completely wrong? I want to encapsulate my directive with controller. I do not want to create any controller on module.

lex82
  • 11,173
  • 2
  • 44
  • 69
Suhas Deshpande
  • 715
  • 1
  • 6
  • 17
  • Possible duplicate of [Unit testing a directive that defines a controller in AngularJS](http://stackoverflow.com/questions/17624315/unit-testing-a-directive-that-defines-a-controller-in-angularjs) – lex82 Dec 28 '15 at 20:39
  • Hey. What was your solution to this? I need to do exactly this, but the answer below doesn't work for me and you have not indicated that that was the correct answer. How did you solve this? – pdschuller Jun 20 '16 at 18:25

1 Answers1

1

Just write

$compile(directiveElement)(vm);

and don't assign the result to directiveElement.

See also the answer to this question on stackoverflow.

Community
  • 1
  • 1
lex82
  • 11,173
  • 2
  • 44
  • 69