Home  >  Article  >  Web Front-end  >  Implement custom services using AngularJS

Implement custom services using AngularJS

一个新手
一个新手Original
2017-09-23 09:54:311689browse

Let’s take cookies as an example.

Step one: First open the console and use bower to install angular-cookies

bower --save angular-cookies

Step two: Create a cache.js file in the service directory.

Step 3: Introduce the angular-cookies module into index.html.

Step 4: Add ngCookies dependency in app.js.

'use strict'angular.module('app',['ui.router','ngCookies']);

Step 5: Call the $cookies service in cache.js

Method one: service service method

'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);
    };
}]);

Method two: facotry service factory method

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.

Step 6: When using it, declare this service cache in the controller controller, such as

'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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn