为什么在Angular中使用服务?
发布时间:2020-12-17 07:43:36 所属栏目:安全 来源:网络整理
导读:我刚刚开始用Angular.阅读Google文档中的一个服务的例子,我只是想知道为什么你会选择使用一个服务,而不是在控制器中保留变量和功能? angular. module('MyServiceModuleDI',[]). factory('notify',function($window) { var msgs = []; return function(msg)
我刚刚开始用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); }; } 在这种情况下你什么时候选择使用服务?
在我看来,主要原因是:
>在控制器之间保持和共享数据. 这是一个例子: 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. }]); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |