1

I am new to Angular JS.I am trying to gain some in depth knowledge in it by understanding the controller functionality.

I came across the following code snippets.

var App = angular.module('clientApp', ['ngResource', 'App.filters']);
 App.controller('ClientCtrl', ['$scope',function ($scope) {

   }]);

What significant difference does it make if i write :

 var App = angular.module('clientApp', ['ngResource', 'App.filters']);
 App.controller('ClientCtrl', function ($scope) {

   });

My Understanding: I do understand that something written in the square brackets is dependency for that particular module or controller.However,I couldnot understand the reason for writing

          "['$scope',function($scope)" 

instead of

   App.controller(controllername,function($scope){

   });

Any help wouls be highly appreciated!

2
  • you don't have to do that, and in fact i think it makes angular code a lot harder to scan/read. i don't mind libs and other black boxes using it (for min), but i don't think the (hopefully) tiny application files will slow down startup because they aren't minified... Commented Apr 9, 2016 at 21:56
  • Did you try my answer? Commented Apr 11, 2016 at 13:12

2 Answers 2

1

It enables AngularJS code to be minified. AngularJS uses parameter names to inject the values to your controller function. In JavaScript minification process, these parameters are renamed to shorter strings. By telling which parameters are injected to the function with a string array, AngularJS can still inject the right values when the parameters are renamed.

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

Comments

1

It should actually be written like this according to the John Papa Style Guide:

First we create and name a module called 'app'. We also create a controller called 'SomeController'.

angular
    .module('app')
    .controller('SomeController', SomeController);

Now we inject the dependencies we require into the controller

SomeController.$inject = ['dataservice', 'logger'];

Now we create the corresposnding function for the controller. Notice how the dependencies are included?

function SomeController(dataservice, logger) {
    var vm = this;
    vm.avengers = [];

    activate();

    function activate() {
        return getAvengers().then(function() {
            logger.info('Activated Avengers View');
        });
    }

    function getAvengers() {
        return dataservice.getAvengers()
            .then(function(data) {
                vm.avengers = data;
                return vm.avengers;
            });
    }
}

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.