1

I'm using ant to build/uglyfy my AngularJS and each time I have a controller in a directive, I get an undefined $scope error. Example of code is this:

app.directive('directive1',['$compile', '$http',function($compile, $http) {
    return {
        restrict: "A",
        controller : function($scope) {
            var posts = {};
            this.addPosts = function($scope, newPosts) {

                angular.extend(posts, newPosts);
                //$scope.$apply(function() {
                    $scope.posts = posts;
                //});
            };
        },
        link: function (scope, element, attrs) {
           scope.posts = {};
        }
    };
}]);

My question is, how can I define the $scope of the controller to when it is compiled it doesn't come up as undefined?

2 Answers 2

1

You want to apply the same minifier/ulgifier safe approach you did on the directive definition to your controller.

So your controller goes from:

controller : function($scope) {

to:

controller: ['$scope',function($scope) {

The uglifier is renaming $scope to something short like 'e' which is great for size but Angular doesn't know what to inject into 'e'.

The uglifier won't change a string. So the new code, above, lets angular know it should inject $scope into 'e' (or whatever name the uglifier gives it).

Sign up to request clarification or add additional context in comments.

2 Comments

You shouldn't need to, directive controllers have a set number of args. They are not freely injectable as a real controller is.
Actually, I'm wrong. This has changed... what I said used to be true but now angular actually does support injection and bracket notation.
0

this.addPosts = function($scope, newPosts) {

What is calling this function? Why are you trying to pass $scope into it? I think you should change it to:

$scope.addPosts = function(newPosts) {

Because you want to get the first $scope... not whatever scope you're attempting to pass into addPosts.

2 Comments

Not the problem or concern, the problem is the $scope does not persist when uglyfied. It works otherwise.
It might be your problem. A minifier will rewrite the first arg of controller as something like function(a) then the addPosts function will get minified as function(b, c)... I can't tell why you're writing your addPosts function like that. Can you explain why it's passing $scope into addPosts? That's just... odd.

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.