最近我一直在学习 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']);
如果依赖项仅传递到函数中而不是首先在数组中声明,这是否意味着库未预加载,这样做是否有好处(这次没有在 app.js 中声明calculatorService):
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 必须是字符串
,ArrayOfDependencies
是包含字符串或回调函数的数组。
例如,如果您想声明一个名称为 myApp 的 Angular module
,该模块依赖于另一个 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!
要回答您的问题,您需要知道什么类型依赖项可以注入(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]
,因为 $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)所有依赖项吗?
答:当然可以,只要您需要。但请确保将它们注入(inject)到正确的位置。
问:如果依赖项仅传递到函数中而不是首先在数组中声明,这是否意味着库未预加载,这样做有好处吗?
答:正如我所提到的, Angular 对象的第二个参数可以接受一个数组,并且该数组可以接受回调函数。然而,如果您只提供一个回调函数,那么稍后当您缩小 JavaScript 代码时就会遇到问题。
如果你这样写,当 JavaScript 缩小时你的应用程序将会崩溃:
angular.module('myApp')
.controller('demoCtrl',function($scope){}); //will break
如果你这样写,当 javascript 缩小时,你的应用不会中断:
angular.module('myApp')
.controller('demoCtrl',['$scope',function($scope){}]
问:这些模块的声明方式有什么不同吗?
答:不。请看以下内容:
angular.module('myApp',[])
.controller('demoCtrl',['$scope',function($scope){}]
上面的代码可以这样写,它们相同:
var app = angular.module('myApp',[]);
app.controller('demoCtrl',['$scope',function($scope){}]
关于javascript - Angular 依赖性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37609210/