Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm unit testing one of my directives. Its basic structure is like this

angular.module('MyApp')
.directive('barFoo', function () {
    return {
        restrict: 'E',
        scope: {},
        controller: function ($scope, $element) { 
              this.checkSomething = function() { .... }
        },
        link: function(scope, element) { .... }
    }
});

In my unit test I want to test the function 'checkSomething', so I tried

var element = $compile('<barFoo></barFoo>')(scope);
var controller = element.controller()
...

However, controller is undefined. Is it possible to access the controller of the directive ?

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

the glue is your scope so you can do

controller: function ($scope, $element) { 
  this.checkSomething = function() { .... }
  $scope.controller = this;                
},

but i think it would be best practice to attach every function to the scope like

controller: function ($scope, $element) { 
  $scope.checkSomething = function() { .... }
},

and then its

var element = $compile('<barFoo></barFoo>')(scope);
var checksomthingResult = scope.checkSomething ()
share|improve this answer
 
I wonder if attaching everything to the scope might influence performance. Or are only $scope properties checked/monitored which are bind/$watched ? –  Jeanluca Scaljeri 17 hours ago
1  
Not all of them. Only those which you have a $watch expression or a binding on them. –  Olivér Kovács 16 hours ago
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.