Service 和 Factory
Angular鼓励程序员来把业务逻辑和数据分开来写。
Service
app.service('MyService', function () {
this.helloWorld = function () {
console.log('Hello World');
};
});
Factory
// The code below is a factory.
app.factory('MyService', function () {
return {
helloWorld: function () {
console.log('Hello World');
};
}
});
通过上面的代码可以看出来,Service
是一个constructor function
,factory
是一个函数。但实际上通过阅读源代码来看,Service
也调用了Factory
:
// By calling service() you are also calling a predefined factory() within AngularJs
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}