AngularJS - 不同的方法来创建控制器和服务,为什么? [英] AngularJS - different ways to create controllers and services, why?
问题描述
我一直看到创造AngularJS控制器和服务的不同的例子,我很困惑,任何人都可以向我解释这两种方法之间的区别?
app.service('reverseService',函数(){
this.reverse =功能(名称){
返回name.split()()反向()加盟。
};
});app.factory('reverseService',函数(){
返回{
反向:函数(名称){
返回name.split()()反向()加盟。
}
}
});
也是一个控制器,例如:
函数ExampleCtrl($范围){
$ scope.data =一些数据;
}app.controller(ExampleCtrl功能($范围){
$ scope.data =一些数据;
}
第一个将污染<一个href=\"http://stackoverflow.com/questions/8862665/what-does-it-mean-global-namespace-would-be-polluted\">global命名空间,这是不是你从长远来看想要的东西。
函数ExampleCtrl($范围){
$ scope.data =一些数据;
}
第二个作用域控制器到该模块实例。这使得它也注射。更妙的是使用数组符号(如下),因为这将生存缩小。
app.controller(ExampleCtrl,['$范围',函数($范围){
$ scope.data =一些数据;
}]);
一个(角)业务和工厂之间的差别似乎很小。服务封装了一个工厂,它使用 $ injector.instantiate 以初始化服务。
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("");
}
}
});
And also a controller example:
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";
}]);
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屋!