0

Here is a angular code from this page: http://docs.angularjs.org/guide/controller

1 var myApp = angular.module('myApp',[]);
2 
3 myApp.controller('GreetingCtrl', ['$scope', function($scope) {
4     $scope.greeting = 'Hola!';
5 }]);

On line #3 above, what is the purpose of the string '$scope'?

Can't I just do this? myApp.controller('GreetingCtrl', function($scope) { ... })

What is the benefit of having an array and the name of the argument there?

2 Answers 2

3

The reason for the argument is to make sure that the angular dependency injector can identify the object to inject if the code is minified.

See A Note on Minification section on the angular site.

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

2 Comments

Thanks for your answer! I accepted a different answer because it contained a bit more information. Thanks!
I thought the internet was getting full so didn't want to duplicate what was already on the angular site on here ;)
1

Yes you can definitely write it myApp.controller('GreetingCtrl', function($scope) { ... }) .

Both ways are right.

The difference is that you are inline annotating the function, so that when you minify your script your dependencies work fine.

When you write $scope as an argument to the function, the angular compiler injects the scope variable in your controller. And it has to be only the $cope nothing else.

So when you minify your script the name of variables get changed. So in normal case your script wont work if you change the name variables. So you write the actual name of variables in the array notation( This the way to annotate in angularJS).

Check Angular JS official document:[Angular JS Dependency Injection1

1 Comment

There is a pretty neat github.com/btford/grunt-ngmin that allows you to write the less-verbose version, which is then filled in with the minification-safe version during a build process.

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.