最近我一直在学习 Angular 并且进展顺利,但是关于依赖注入(inject)的一些事情我仍然不清楚。
是否有任何理由在我的 app.js 文件中声明我的应用程序的其他部分(服务、 Controller 等)?
似乎有时教程会显示这一点,有时却不会:
var calculatorApp = angular.module('calculatorApp', [
'config',
'ngRoute',
'calculatorControllers', //Do I need to declare these comnponents here?
'calculatorServices'
]);
同样,我是否需要在 app.js 中声明整个应用程序的所有依赖项?看来我也可以在任何模块中声明依赖项(这里 ngResource 没有在 app.js 中声明,只是在 services.js 中声明):
var calculatorServices = angular.module('calculatorServices', ['ngResource']);
如果依赖项只传递给函数而不是首先在数组中声明,这是否意味着库没有预加载,这样做有好处吗(这次 calculatorService 没有在 app.js 中声明):
angular.module('myApp')
.controller('MainCtrl', function ($scope, $location, calculatorService)
最后,这些模块的声明方式有什么不同吗?第一个不引用主模块,第二个示例引用:
var calculatorServices = angular.module('calculatorServices', ['ngResource']);
angular.module('myApp')
.controller('MainCtrl', function ($scope, $location, calculatorService)
一般经验法则:第一个参数是名称,第二个参数是依赖项列表。
一般来说,AngularJs 有一个非常标准的做事方式。 Angular 对象的所有声明都遵循相同的约定:
angular.Object(NameOfObject,ArrayOfDependencies[])
其中 NameOfObject 必须是 sợi dây
,ArrayOfDependencies
是包含字符串或回调函数的数组。
例如,如果你想声明一个名为 myApp 的 Angular module
,它依赖于khác angular module
的名称为 ngAnimate,您执行以下操作:
angular.module('myApp',['ngAnimate']);
如果您无法想象它,让我们分解成几个部分。下面的代码和上面的单行代码是一样的。
var myModuleName = "myApp"; //this is your app name
var myDependenciesArray= ['ngAnimate']; // this is a list of dependencies your app is gonna depend on
angular.module(myModuleName,myDependenciesArray); //voila, module declared!
要回答您的问题,您需要知道哪些kiểu 依赖项可以注入(inject)到哪些 Angular 对象中。你不能混淆。
module
只能接受另一个模块的注入(inject),不能接受服务类型(准确的说是提供者类型)。下面的语法是正确的:
angular.module('module1',[]);
angular.module('module2',['module1']) // this is okay, module 2 depends on module1.
如果你这样做:
angular.module('module2',['$http']) //this is NOT okay
你会得到 Angular 抛出的 [$injector:modulerr]
bởi vì $http
是服务名称而不是模块名称。
出于同样的原因,如果您没有声明模块,那么您不能在该声明中注入(inject)模块,而必须注入(inject)服务。以下语法是正确的:
angular.module('demo')
.controller('myCtrl',['$scope',function($scope){}] // this is okay, your controller depends on the $scope service
如果你这样做:
angular.module('demo')
.controller('myCtrl',['ngResource']) // this is NOT okay
你会得到 Angular 抛出的 [$injector:unpr]
,声明没有找到这样的提供者。
让我们来回答您的问题:
问:需要注入(inject)所有的依赖吗?
A:当然可以,只要你需要。但请确保将它们注入(inject)到正确的位置。
问:如果依赖项仅传递到函数中而不是首先在数组中声明,这是否意味着库未预加载,这样做有好处吗?
A:正如我所提到的, Angular 对象的第二个参数可以接受一个数组,并且该数组可以接受回调函数。但是,如果您只提供一个回调函数,那么稍后在缩小 JavaScript 代码时就会遇到问题。
如果你这样写,当 javascript 被缩小时,你的应用程序将崩溃:
angular.module('myApp')
.controller('demoCtrl',function($scope){}); //will break
如果您这样写,当 javascript 被缩小时,您的应用sẽ không中断:
angular.module('myApp')
.controller('demoCtrl',['$scope',function($scope){}]
问:这些模块的声明方式有什么不同吗?
A:没有。看看下面的:
angular.module('myApp',[])
.controller('demoCtrl',['$scope',function($scope){}]
上面的代码可以这样写,它们như nhau:
var app = angular.module('myApp',[]);
app.controller('demoCtrl',['$scope',function($scope){}]
Tôi là một lập trình viên xuất sắc, rất giỏi!