AngularJS : minification issue in directive

让人想犯罪 __ 提交于 2020-01-20 17:09:13

问题


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 ?


回答1:


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.




回答2:


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 ?



来源:https://stackoverflow.com/questions/16055449/angularjs-minification-issue-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!