我最近开始使用 angularjs。但模块的概念让我感到困惑。
在其中一个 Angular 教程中,有以下代码:
'use strict';
/* Services */
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
//this line's added by me
phonecatServices.constant('SomeConstant', 123);
phonecatServices.factory('Phone', ['$resource',
function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
}]);
为什么 AngularJS 需要像常量或工厂这样的辅助函数,因为它可以以类似于 NodeJS 的方式定义模块,这样更干净?我很困惑这种方法有什么优点。
var $resource = require('$resource');
var SomeConstant = 123;
var Phone = $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
};
exports.SomeConstant = SomeConstant;
exports.Phone = Phone;
最佳答案
答案似乎集中在 Angular 的依赖注入(inject)上。
将 angular.module
视为 api说,创建/注册或检索模块的全局方法。需要以这种方式创建一个模块,因此 $injector
,这是一个获取已注册的模块名称列表的函数,可以在bootstrapping时找到它。 。
我不会将 factory
函数视为“助手”,而实际上是一种指定 Angular js 依赖注入(inject)如何创建服务的方法。或者如dependency injection guide这么说——我们正在“教导”$injector 如何创建服务:
// Provide the wiring information in a module
angular.module('myModule', []).
// Teach the injector how to build a 'greeter'
// Notice that greeter itself is dependent on '$window'
factory('greeter', function($window) {
// This is a factory function, and is responsible for
// creating the 'greet' service.
return {
greet: function(text) {
$window.alert(text);
}
};
});
// New injector is created from the module.
// (This is usually done automatically by angular bootstrap)
var injector = angular.injector(['myModule', 'ng']);
// Request any dependency from the injector
var greeter = injector.get('greeter');
指南还提醒我们,这里的注入(inject)器是直接从模块创建的,但通常 Angular 的 Bootstrap 会为我们处理这个问题。
所以,简而言之,angular.module
告诉 Angular 如何解析模块(它通过 $injector
完成),以及 factory
告诉 Angular 如何在需要时制作它们。相比之下,Node 的模块与文件具有一对一的映射,并在 this way 中解析和制作。 .
关于javascript - 为什么需要使用工厂函数指定 Angular 模块,而不是像我指定 Node 模块那样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21575372/