AngularJS - 创建控制器和服务的不同方式,为什么? [英] AngularJS - different ways to create controllers and services, why?
问题描述
我一直看到在 AngularJS 中创建控制器和服务的不同示例,但我很困惑,谁能向我解释这两种方法之间的区别?
I keep seeing different examples of creating controllers and services in AngularJS and I'm confused, can anyone explain to me the differences between the two approaches?
app.service('reverseService', function() {
this.reverse = function(name) {
return name.split("").reverse().join("");
};
});
app.factory('reverseService', function() {
return {
reverse : function(name) {
return name.split("").reverse().join("");
}
}
});
还有一个控制器示例:
function ExampleCtrl($scope) {
$scope.data = "some data";
}
app.controller("ExampleCtrl", function($scope) {
$scope.data = "some data";
}
推荐答案
第一个会污染全局命名空间,从长远来看这不是你想要的.
The first one will pollute the global namespace, which is not what you want in the long run.
function ExampleCtrl($scope){
$scope.data = "some data";
}
第二个将控制器的范围限定为该模块实例.它也使它可注射.最好还是使用数组表示法(如下所示),因为这样可以在缩小后幸存下来.
The second one scopes the Controller to that module instance. It makes it also injectable. Better still is using the array notation (as below), since this will survive minification.
app.controller("ExampleCtrl", ['$scope', function($scope){
$scope.data = "some data";
}]);
(角度)服务和工厂之间的区别似乎很小.一个服务包装了一个工厂,它使用 $injector.instantiate 来初始化服务.
The difference between an (angular) service and factory seems quite small. A service wraps a factory, which uses $injector.instantiate to initialize the service.
这篇关于AngularJS - 创建控制器和服务的不同方式,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!