Iamsamstimpson
Iamsamstimpson

Reputation: 1357

Angular scope, scope?

I'm learning Angular and was just explaining to a colleague about controllers when they asked why $scope was passed in twice

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

Can anyone enlighten us?

 myApp.controller('appList', ['$scope', function($scope) {
        $scope.things = [
            {
                "name":"Cheese",
                "id":"1",
                "short-name":"ch"
            },
            {
                "name":"Bread",
                "id":"2",
                "short-name":"br"
            },
            {
                "name":"Wine",
                "id":"3",
                "short-name":"wi"
            }
        ];
    }]);

This example we were writing is overly simple we know.

Upvotes: 2

Views: 149

Answers (1)

Philipp Gayret
Philipp Gayret

Reputation: 5070

You don't have to pass an array. It has to do with minification, it's noted in the AngularJS tutorial, when you minify code like this

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

The minifyer will do it's best to rename things to make your code as small as possible, that includes parameters, so your line of code could end up like this for example

['$scope',function(a){

Now the $scope parameter has been renamed, but AngularJS still knows that you want something injected with the name $scope, not a. If you don't make this list yourself and minify your code, AngularJS can't read the function parameter list and will not know what to inject into your ( in your example ) controller.

There's tool that automate this listing, you could integrate those with any build tools you might be using, to automate the whole process of listing dependencies as string explicitly, and minifying.

Upvotes: 1

Related Questions