0

I am learning AngularJS DI concept, Can anyone tell me why below code not working?

<script type="text/javascript">

        var myApp = angular.module('myApp',[])

    var myController = myApp.controller('MyController', function(a){
        a.name = 'william'
        console.log(a.name)
    })

    myController.$inject = ['$scope']

    </script>

Iam getting an error as: https://docs.angularjs.org/error/$injector/unpr?p0=aProvider%20%3C-%20a

In above code, in place of 'a', if replaced with '$scope', it definitely works. As far as I understand, angular should inject $scope into 'a' parameter, right?

2 Answers 2

1

$inject must be defined on the controller, not on the module:

var ctrl = function(a) { ... };
ctrl.$inject = ['$scope'];
myApp.controller('MyController', ctrl);

But I strongy suggest you

  • use $scope for your variable rather than a
  • let ng-annotate transform the code to minifiable code automatically.
Sign up to request clarification or add additional context in comments.

7 Comments

I updated my code, still not injecting..whats the problem? BTW, when should I use ng-annotate?
Sorry. Mistake on my side. See the edited answer. plnkr.co/edit/DKUS15Qn4XwvjBmXfIus?p=preview
In your code, you have created some function and then at line 7, you have declared as myController.$inject = ['$scope'] , but why does it not give an error at this line ? The reason i asked because $inject belongs to angularjs, right? myController is just a function, so how does a normal function can call $inject directly?
A function is also an object in JavaScript, and can thus have arbitrary, dynamically assigned attributes, like $inject.
okay fine. But I do not understand one thing, Why does my code not working? I mean why injecting getting failed in my case..whats the differnce between your code and mine? you first created function outside and then used it inside .controller, right? Could you please explain briefly?
|
0

$inject should be on controller function:

    var myApp = angular.module('myApp',[])

    myApp.controller('MyController', function myController(a){
        a.name = 'william'
        console.log(a.name)
    })

    myController.$inject = ['$scope']

Comments

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.