2

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 ?

1 Answer 1

1

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 ()
Sign up to request clarification or add additional context in comments.

2 Comments

I wonder if attaching everything to the scope might influence performance. Or are only $scope properties checked/monitored which are bind/$watched ?
Not all of them. Only those which you have a $watch expression or a binding on them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.