在我看来,主要原因是:
在控制器之间持久化和共享数据。
IE:您创建了一个从数据库中获取数据的服务,如果您将其存储在控制器中,一旦您更改为另一个控制器,数据将被丢弃(除非您将其存储在 $rootScope 但这不是最好的方法it) ,但是如果你把它保存在一个服务中(服务是单例的),当你更改控制器时,数据将保持不变。
通过创建将由您的控制器/指令/服务使用的 API 来抽象数据访问逻辑。
将业务逻辑保留在控制器中,将数据逻辑保留在服务中。
干燥(不要重复自己)。
IE:您在不同的控制器中有一系列您需要的功能,如果没有服务,您将不得不在每个控制器中重复您的代码,使用服务您可以为这些功能创建一个 API 并将其注入每个控制器/指令/您需要的服务。
这是一个例子:
var myApp = angular.module('myApp',[]);
//Here is the service Users with its functions and attributes
//You can inject it in any controller, service is a singleton and its data persist between controllers
myApp.factory('Users', function () {
//data logic
//fetch data from db and populate...
var name = "John";
var surname = "Doe"
function getName() { return name; }
function getFullName() { return name + ' ' + surname; }
function setName(newName) { name = newName; }
//API
return {
getName: getName,
getFullName: getFullName,
setName: setName
}
});
//An Util service with methods I will use in different controllers
myApp.factory('Util', function () {
//a bunch of useful functions I will need everywhere
function daysInMonth (month,year) {
return new Date(year, month+1,0).getDate();
}
return {
daysInMonth: daysInMonth
};
});
//Here I am injecting the User and Util services in the controllers
myApp.controller('MyCtrl1', ['$scope', 'Users', 'Util', function ($scope, Users, Util) {
$scope.user = Users.getFullName(); //"John Doe";
Users.setName('Bittle');
//Using Util service
$scope.days = Util.daysInMonth(05,2013);
}]);
myApp.controller('MyCtrl2', ['$scope', 'Users', 'Util', function ($scope, Users, Util) {
$scope.user = Users.getFullName(); //"Bittle Doe"; //The change that took place in MyCtrl1 hhas persisted.
}]);