0

Two code samples:

First:

var app = angular.module('MyApp', []);
app.controller('MyCtrl', function($scope){
    $scope.equation = {};
    $scope.change = function() {
        $scope.equation.output = Number($scope.equation.x) + 2;
    }
});

Second:

var app = angular.module('MyApp', []);
app.controller('MyCtrl', ['$scope', function($scope){
    $scope.equation = {};
    $scope.change = function() {
        $scope.equation.output = Number($scope.equation.x) + 2;
    }
}]);

I currently have both of them working.

What's with the [] enclosing the callback in the second sample? And what is different between these implementations?

4

1 回答 1

3

因为 Angular 使用依赖注入,它会读取方法的参数名称并使用反射来注入您要注入的服务

缩小的情况是它基本上重命名了参数名称并缩短了它们,所以你的第一个例子没有用[],为什么?

因为使用数组指定参数名,会匹配数组param到函数params

例子

// 1- using the array notation
app.controller('MyCtrl', ['$scope', function(z) {} ]);
// 'z' this will be '$scope' the actual name will be taken from the array not the parameter name

// 2- using the normal notation (this is similiar to what will be producted by the minifier if you didn't use the array notation
app.controller('MyCtrl', function(z /* what is this ? */ ) {} );
// the code will fail because angular doesn't understand what 'z' means and has no way to map to anything else

查看这篇文章了解更多详情


你应该用什么?

因此您可以使用该[]示例使您的代码与缩小一起使用,或者您使用一个名为ngmin的节点包,它基本上会重构您的代码并将其转换为使用[]符号(注意:它在一些极端情况下会失败)但通常可以工作

于 2013-11-05T21:03:22.007 回答