【问题标题】:AngularJs - injecting $scopeAngularJs - 注入 $scope
【发布时间】:2016-07-17 12:43:52
【问题描述】:

下面两个例子是等价的吗?

1.

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

2.

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

我是 AngularJs 的新手。根据我的测试,他们做同样的事情,但不知道为什么会有两种不同的方式。

【问题讨论】:

标签: angularjs angularjs-scope angularjs-injector


【解决方案1】:

Dependency Injection 是 Angular js 的一大特色,用于 JS 缩小时,

JS 缩小前: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

       });

JS 缩小后: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.

   });

【讨论】:

    【解决方案2】:

    它们都是等效的,并且可以正常工作。您可以选择其中一个,具体取决于您计划对项目进行的操作。使用第二种表示法对缩小非常重要,这称为 Inline Array Annotation 或更普遍地称为 Dependency Annotation

    您可以在 AngularJS 文档here 中找到有关依赖注入的详细信息。

    【讨论】:

      【解决方案3】:

      它们的功能相同,但通常首选第二种方法。这与缩小有关,并且当您分发应用程序时,如果变量名称不是数组中的项目,则变量名称可能会被更改。

      当然,如果您的控制器名称在缩小期间发生更改,这将导致 Angular 的依赖注入失败。

      【讨论】:

        猜你喜欢
        • 2014-03-02
        • 1970-01-01
        • 2016-08-06
        • 2015-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多