gpt4 book ai didi

angularjs - AngularJS 中 Controller 声明的区别

转载 作者:行者123 更新时间:2023-12-01 08:25:58 25 4
gpt4 key购买 nike

我看到 Controller 以如下两种方式声明。但这有什么区别呢?

  1. appmodule.controller('Actrl',['$scope',function($scope) {}]);
  2. appmodule.controller('Actrl',function($scope) {});

但是,大多数时候,第一个不起作用。为什么?

最佳答案

两种语法相同,但首选第一种 (有错字,请参阅下面的说明) ,如果您要缩小代码。

Angular 根据名称解析依赖,所以当你编写 appmodule.controller('Actrl',function($scope) {}); 语法时,Angular 会注入(inject) $ 的依赖scope 通过读取参数名称 $scope。但是,当您的代码被缩小以供生产级使用时,您的代码将变为:

appmodule.controller('Actrl', function(a) {});

现在,Angular 将无法解析名称为 a 的依赖项。这就是使用第一种方法的原因,即 appmodule.controller('Actrl',['$scope', function($scope) {}]);。现在,当您的代码被最小化以用于生产时,您的代码将是这样的:

 appmodule.controller('Actrl',['$scope', function(a) {}]);

现在,Angular 可以匹配 a$scope 的基于索引的位置。

您的代码中有一个错字,在 function 声明之前不应关闭列表。

阅读 Dependency AnnotationInline Array Annotation 主题下了解更多信息。

Angular invokes certain functions (like service factories and controllers) via the injector. You need to annotate these functions so that the injector knows what services to inject into the function. There are three ways of annotating your code with service name information:

  • Using the inline array annotation (preferred)
  • Using the $inject property annotation
  • Implicitly from the function parameter names (has caveats)

编辑:对两种不同风格的另一个更详细的描述:a-note-on-minification :

Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.

We can overcome this problem by annotating the function with the names of the dependencies, provided as strings, which will not get minified. There are two ways to provide these injection annotations:

关于angularjs - AngularJS 中 Controller 声明的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35336180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com