32

I have yet another issue with minification. This time it's because of the $scope service passed to the directive's controller. See below code:

angular.module('person.directives').
directive("person", ['$dialog', function($dialog) {
return {
    restrict: "E",
    templateUrl: "person/views/person.html",
    replace: true,
    scope: {
        myPerson: '='
    },     
    controller: function ($scope)
    {                   
        $scope.test = 3;                   
    }
}
}]);

If I comment out the controller part, then it works fine.

As you can see, I've used the array declaration for the directive, so the $dialog service is known to Angular even after minification. But how am I supposed to do it for the $scope service on the controller ?

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Sam
  • 13,934
  • 26
  • 108
  • 194

2 Answers2

75

You need to declare a controller as follows:

controller: ['$scope', function ($scope)
    {                   
        $scope.test = 3;                   
    }]

Full example here:

angular.module('person.directives').
directive("person", ['$dialog', function($dialog) {
return {
    restrict: "E",
    templateUrl: "person/views/person.html",
    replace: true,
    scope: {
        myPerson: '='
    },     
    controller: ['$scope', function ($scope)
    {                   
        $scope.test = 3;                   
    }]
}
}]);

A solution provided by @Sam would work to but it would mean exposing directive's controller to the whole application which is unnecessary.

pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
  • that's the solution provided by me :) Sam = OP ;-) However I'm not exposing the controller to the whole application, just to the whole module that the directive belongs to. I like your approach though, I'll go for that. – Sam Apr 17 '13 at 09:05
  • Actually exposing it to one AngularJS module would mean that _any_ AngularJS module would have access to it - this is what I've meant by exposing it to the whole application. – pkozlowski.opensource Apr 17 '13 at 09:07
  • AngularJS modules would have access to the person.controllers module only if they depend on it. If they don't have that dependency, they should not be able to access it. Isn't that right ? – Sam Apr 17 '13 at 09:13
  • Nope, in the current version of AngularJS those controllers would be available globally, in the whole application. – pkozlowski.opensource Apr 17 '13 at 09:26
  • Wow that had me stumped for a while! Thanks – Rob B Jan 07 '14 at 15:15
  • Great solution to wrap it like this... Thanks for this. – error505 Nov 07 '16 at 09:36
1

ok, I ended up creating the controller in a separate file :

angular.module('person.controllers').controller('personCtrl', ['$scope', function ($scope) {
$scope.test = 3;
}]);

then in the directive, I assign the controller by name:

controller: 'personCtrl'

Not sure it's the best way. It looks clean though. What do you think ?

Sam
  • 13,934
  • 26
  • 108
  • 194