Leahcim
Leahcim

Reputation: 42069

How to inject dependencies when controller set up as a regular function

In one of the many Angularjs style guides, it suggests setting up a controller like this

function myCtrl(dependency1, dependency2){

}
module.controller('MyCtrl', MyCtrl);

I tried it by doing the following, in which I also use a $watch on the $scope. However, I get an error that $watch is not a function, so I'm assuming that I'm not injecting the scope properly.

This is the code in my app/controllers/myctrl.js file

function MyCtrl($scope, myStorage){
         var mystore = $scope.mystore = myStorage.get();
         $scope.$watch('mystore', function(){
                 //code ommitted
         } 
}
angular.module('myApp').controller('MyCtrl', MyCtrl);

Question, How do I inject $scope and other dependencies using this style?

Previously, I did it this way and everything worked fine.

 angular.module('myApp').controller('MyCtrl', ['$scope', 'myStorage',
             function MyController($scope, myStorage){

             }
       ]);

Upvotes: 0

Views: 87

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40318

MyCtrl.$inject = ['dependency1', 'dependency2'];
function MyCtrl(dependency1, dependency2){

}

Yes, it can come before the function (just like an annotation in Java).

Upvotes: 2

Related Questions