Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Service Injection

I am working on a trivial task (that I got working) which adds an an .active class to dom elements in a tab nav. Simple. Got it working by following https://stackoverflow.com/a/12306136/2068709.

Reading over the answer provided and comparing their controller to example controllers on angular's website I came across something interesting that I don't quite understand.

On the AngularJS website, $scope and $location (and other services) are injected into the controller along with an anonymous function which defines the controller. But on the answer, the services are not injected, rather they are passed via the anonymous function. Why does this work? Shouldn't the service always be injected?

In terms of an example: Why does this

angular.module('controllers', [])
    .controller('NavigationController', ['$scope', '$location', function($scope, $location) { 
        $scope.isActive = function(route) {
            return route === $location.path();
        };
    }])

and this

angular.module('controllers', [])
    .controller('NavigationController', function($scope, $location) { 
        $scope.isActive = function(route) {
            return route === $location.path();
        };
    })

both work?

This may be trivial but its throwing my brain for a loop that I can't figure out.

like image 220
pattmorter Avatar asked Aug 09 '26 01:08

pattmorter


1 Answers

The two examples are equivalent - they just make use of different syntax. The first example uses what they call "inline array annotation" (see here). The purpose of this alternate syntax is just to allow a convenient way to make the injected variable names different than the name of the dependency.

So for example, if you wanted the variable names to be "s" and "l", then you could write:

angular.module('controllers', [])
    .controller('NavigationController', ['$scope', '$location', function(s, l) { 
        s.isActive = function(route) {
            return route === l.path();
        };
    }]);
like image 127
McGarnagle Avatar answered Aug 10 '26 14:08

McGarnagle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!