2

Are the two examples below equivalent?

1.

app.controller('ctrl',function($scope){});

2.

app.controller('ctrl',['$scope',function($scope){});

I'm new to AngularJs. From my test, they do the same thing, but not sure why there are two different ways.

1

3 Answers 3

2

They will function the same way, but usually the second method is preferred. This has to do with minification and the fact that when you distribute your app it's a possibility variable names will be changed if they aren't items within an array.

Of course if your controller names change during minification this will cause Angular's dependency injection to fail.

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

Comments

2

Dependency Injection is a great feature of angular js used on when do JS minification,

Before JS Minification: ctrl.js

app.controller('ctrl'['$scope','$rootScope','$state',function($scope,$rootScope,$state){
    $scope.message="Hello World"; //Must be maintain serial of Dependency Injection either wise show error

       });

After JS Minification: ctrl.min.js

app.controller('ctrl'['$scope','$rootScope','$state',function(a,b,c){
a.message="Hello World";
    //So do not write $scope again just define 'a' instead of '$scope' like as $rootScope=b,$state=c ,so huge memory save in JS file.

   });

Comments

1

They are both equivalent and will work just fine. You may choose one over the other, depending on what you are planning on doing with your project. It is primarily important for minification to use the second notation, which is called Inline Array Annotation or more generally Dependency Annotation.

You can find detailed information regarding dependency injection in the AngularJS documentation here.

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.