Home > Article > Web Front-end > Implement custom services using AngularJS
Let’s take cookies as an example.
bower --save angular-cookies
'use strict'angular.module('app',['ui.router','ngCookies']);
'use strict'; angular.module('app').service('cache', ['$cookies', function($cookies){ this.put = function(key, value){ $cookies.put(key, value); }; this.get = function(key) { return $cookies.get(key); }; this.remove = function(key) { $cookies.remove(key); }; }]);
angular.module('app').factor('cache', ['$cookies', function($cookies){ //也就是说factor和service同时声明服务,作用是一样的,它们的区别在于我们调用factor的时候,factor可以在return对象之前可以声明一些私有的属性。如: var obj = {};//相当于一个私有属性,外部不可访问,而直接声明service是没有这个功能的。 //注意:factor和service不同,我们不能再this这个当前对象上面添加属性了,而是返回一个对象 //这个对象所带来的属性就是我们外面引用的factor可以引用的属性 return { put : function(key, value){ $cookies.put(key, value); }; get : function(key) { return $cookies.get(key); }; remove : function(key) { $cookies.remove(key); }; } }]);
That is to say, factor and service declare services at the same time, and their functions are the same. The difference between them is that when we call factor, factor can declare some private attributes before the return object.
When there is no need to declare internal private properties, their functions are the same.
What needs to be remembered is that factor needs to return an object directly, while service can just return a function directly.
'use strict'; angular.module('app').controller('positionCtrl',['$q','$http','$state','$scope','cache',function ($q,$http,$state,$scope,cache) { cache.put('to','day');//存入这个值 cache.remove('to'); //删除}]);
The above is the detailed content of Implement custom services using AngularJS. For more information, please follow other related articles on the PHP Chinese website!