我刚刚开始用Angular.阅读Google文档中的一个服务的例子,我只是想知道为什么你会选择使用一个服务,而不是在控制器中保留变量和功能?
angular. module('MyServiceModuleDI',[]). factory('notify',function($window) { var msgs = []; return function(msg) { msgs.push(msg); if (msgs.length == 3) { $window.alert(msgs.join("\n")); msgs = []; } }; }); function myController($scope,notify) { $scope.callNotify = function(msg) { notify(msg); }; }
在这种情况下你什么时候选择使用服务?
在我看来,主要原因是:
>在控制器之间保持和共享数据.
IE:创建一个从数据库中获取数据的服务,如果将其存储在控制器中,一旦更改为另一个Controller,数据将被丢弃(除非您将它存储在$rootScope中,但这不是最好的方法它),但是如果您将其保留在服务(服务是单身)中,则在更改控制器时,数据将持续存在.
>抽象数据访问逻辑,通过创建一个API将被您的控制器/指令/服务使用.
将业务逻辑保持在服务内部的控制器和数据逻辑中.
> DRY(不要重复你自己).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',Util) { $scope.user = Users.getFullName(); //"Bittle Doe"; //The change that took place in MyCtrl1 hhas persisted. }]);