• 本地存储 cookie,session,localstorage( 二)angular-local-storage


    原文:https://github.com/grevory/angular-local-storage#api-documentation

    Get Started

    (1)Bower: $ bower install angular-local-storage --save

    npm: $ npm install angular-local-storage

    (2) Include angular-local-storage.js (or angular-local-storage.min.js) from the dist directory in your index.html, after including Angular itself.

    (3) Add 'LocalStorageModule' to your main module's list of dependencies.

    When you're done, your setup should look similar to the following:

    <!doctype html>
    <html ng-app="myApp">
    <head>
    </head>
    <body><script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
        <script src="bower_components/js/angular-local-storage.min.js"></script>    
        <script>
            var myApp = angular.module('myApp', ['LocalStorageModule']);
        </script>   
    </body>
    </html>

    Configuration

    setPrefix

    You could set a prefix to avoid overwriting any local storage variables from the rest of your app
    Default prefix: ls.<your-key>

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setPrefix('yourAppName');
    });

    setStorageType

    You could change web storage type to localStorage or sessionStorage
    Default storage: localStorage

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setStorageType('sessionStorage');
    });

    setDefaultToCookie

    If localStorage is not supported, the library will default to cookies instead. This behavior can be disabled.
    Default: true

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setDefaultToCookie(false);
    });

    setStorageCookie

    Set cookie options (usually in case of fallback)
    expiry: number of days before cookies expire (0 = session cookie). default: 30
    path: the web path the cookie represents. default: '/'
    secure: whether to store cookies as secure. default: false

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setStorageCookie(45, '<path>', false);
    });

    setStorageCookieDomain

    Set the cookie domain, since this runs inside a the config() block, only providers and constants can be injected. As a result,$location service can't be used here, use a hardcoded string or window.location.
    No default value

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setStorageCookieDomain('<domain>');
    });

    For local testing (when you are testing on localhost) set the domain to an empty string ''. Setting the domain to 'localhost' will not work on all browsers (eg. Chrome) since some browsers only allow you to set domain cookies for registry controlled domains, i.e. something ending in .com or so, but not IPs or intranet hostnames like localhost. 

    setNotify

    Configure whether events should be broadcasted on $rootScope for each of the following actions:
    setItem , default: true, event "LocalStorageModule.notification.setitem"
    removeItem , default: false, event "LocalStorageModule.notification.removeitem"

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setNotify(true, true);
    });

    Configuration Example

    Using all together

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setPrefix('myApp')
        .setStorageType('sessionStorage')
        .setNotify(true, true)
    });

    API Documentation

    isSupported

    Checks if the browser support the current storage type(e.g: localStoragesessionStorage). Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      if(localStorageService.isSupported) {
        //...
      }
      //...
    });

    getStorageType

    Returns: String

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      var storageType = localStorageService.getStorageType(); //e.g localStorage
      //...
    });

    You can also dynamically change storage type by passing the storage type as the last parameter for any of the API calls. For example: localStorageService.set(key, val, "sessionStorage");

    set

    Directly adds a value to local storage.
    If local storage is not supported, use cookies instead.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      function submit(key, val) {
       return localStorageService.set(key, val);
      }
    });

    get

    Directly get a value from local storage.
    If local storage is not supported, use cookies instead.
    Returns: value from local storage

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function getItem(key) {
       return localStorageService.get(key);
      }
      //...
    });

    keys

    Return array of keys for local storage, ignore keys that not owned.
    Returns: value from local storage

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      var lsKeys = localStorageService.keys();
      //...
    });

    remove

    Remove an item(s) from local storage by key.
    If local storage is not supported, use cookies instead.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function removeItem(key) {
       return localStorageService.remove(key);
      }
      //...
      function removeItems(key1, key2, key3) {
       return localStorageService.remove(key1, key2, key3);
      }
    });

    clearAll

    Remove all data for this app from local storage.
    If local storage is not supported, use cookies instead.
    Note: Optionally takes a regular expression string and removes matching.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function clearNumbers(key) {
       return localStorageService.clearAll(/^d+$/);
      }
      //...
      function clearAll() {
       return localStorageService.clearAll();
      }
    });

    bind

    Bind $scope key to localStorageService. Usage: localStorageService.bind(scope, property, value[optional], key[optional]) key: The corresponding key used in local storage Returns: deregistration function for this listener.

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      localStorageService.set('property', 'oldValue');
      $scope.unbind = localStorageService.bind($scope, 'property');
    
      //Test Changes
      $scope.update = function(val) {
        $scope.property = val;
        $timeout(function() {
          alert("localStorage value: " + localStorageService.get('property'));
        });
      }
      //...
    });
    <div ng-controller="MainCtrl">
      <p>{{property}}</p>
      <input type="text" ng-model="lsValue"/>
      <button ng-click="update(lsValue)">update</button>
      <button ng-click="unbind()">unbind</button>
    </div>

    deriveKey

    Return the derive key Returns String

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      localStorageService.set('property', 'oldValue');
      //Test Result
      console.log(localStorageService.deriveKey('property')); // ls.property
      //...
    });

    length

    Return localStorageService.length, ignore keys that not owned. Returns Number

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      var lsLength = localStorageService.length(); // e.g: 7
      //...
    });

    Cookie

    Deal with browser's cookies directly.

    cookie.isSupported

    Checks if cookies are enabled in the browser. Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      if(localStorageService.cookie.isSupported) {
        //...
      }
      //...
    });

    cookie.set

    Directly adds a value to cookies.
    Note: Typically used as a fallback if local storage is not supported.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function submit(key, val) {
       return localStorageService.cookie.set(key, val);
      }
      //...
    });

    Cookie Expiry Pass a third argument to specify number of days to expiry

        localStorageService.cookie.set(key,val,10)

    sets a cookie that expires in 10 days. Secure Cookie Pass a fourth argument to set the cookie as secure W3C

        localStorageService.cookie.set(key,val,null,false)

    sets a cookie that is secure.

    cookie.get

    Directly get a value from a cookie.
    Returns: value from local storage

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function getItem(key) {
       return localStorageService.cookie.get(key);
      }
      //...
    });

    cookie.remove

    Remove directly value from a cookie.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function removeItem(key) {
       return localStorageService.cookie.remove(key);
      }
      //...
    });

    cookie.clearAll

    Remove all data for this app from cookie.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function clearAll() {
       return localStorageService.cookie.clearAll();
      }
    });

    Check out the full demo at http://gregpike.net/demos/angular-local-storage/demo.html

    Development:

    • Don't forget about tests.
    • If you're planning to add some feature please create an issue before.

    Clone the project:

    $ git clone https://github.com/<your-repo>/angular-local-storage.git
    $ npm install
    $ bower install

    Run the tests:

    $ grunt test

    Deploy:
    Run the build task, update version before(bower,package)

    $ npm version patch|minor|major
    $ grunt dist
    $ git commit [message]
    $ git push origin master --tags

    Get Started

    (1) You can install angular-local-storage using 3 different ways:
    Git: clone & build this repository
    Bower:

    $ bower install angular-local-storage --save

    npm:

    $ npm install angular-local-storage

    (2) Include angular-local-storage.js (or angular-local-storage.min.js) from the dist directory in your index.html, after including Angular itself.

    (3) Add 'LocalStorageModule' to your main module's list of dependencies.

    When you're done, your setup should look similar to the following:

    <!doctype html>
    <html ng-app="myApp">
    <head>
    
    </head>
    <body>
        ...
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
        <script src="bower_components/js/angular-local-storage.min.js"></script>
        ...
        <script>
            var myApp = angular.module('myApp', ['LocalStorageModule']);
    
        </script>
        ...
    </body>
    </html>

    Configuration

    setPrefix

    You could set a prefix to avoid overwriting any local storage variables from the rest of your app
    Default prefix: ls.<your-key>

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setPrefix('yourAppName');
    });

    setStorageType

    You could change web storage type to localStorage or sessionStorage
    Default storage: localStorage

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setStorageType('sessionStorage');
    });

    setDefaultToCookie

    If localStorage is not supported, the library will default to cookies instead. This behavior can be disabled.
    Default: true

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setDefaultToCookie(false);
    });

    setStorageCookie

    Set cookie options (usually in case of fallback)
    expiry: number of days before cookies expire (0 = session cookie). default: 30
    path: the web path the cookie represents. default: '/'
    secure: whether to store cookies as secure. default: false

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setStorageCookie(45, '<path>', false);
    });

    setStorageCookieDomain

    Set the cookie domain, since this runs inside a the config() block, only providers and constants can be injected. As a result,$location service can't be used here, use a hardcoded string or window.location.
    No default value

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setStorageCookieDomain('<domain>');
    });

    For local testing (when you are testing on localhost) set the domain to an empty string ''. Setting the domain to 'localhost' will not work on all browsers (eg. Chrome) since some browsers only allow you to set domain cookies for registry controlled domains, i.e. something ending in .com or so, but not IPs or intranet hostnames like localhost. 

    setNotify

    Configure whether events should be broadcasted on $rootScope for each of the following actions:
    setItem , default: true, event "LocalStorageModule.notification.setitem"
    removeItem , default: false, event "LocalStorageModule.notification.removeitem"

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setNotify(true, true);
    });

    Configuration Example

    Using all together

    myApp.config(function (localStorageServiceProvider) {
      localStorageServiceProvider
        .setPrefix('myApp')
        .setStorageType('sessionStorage')
        .setNotify(true, true)
    });

    API Documentation

    isSupported

    Checks if the browser support the current storage type(e.g: localStoragesessionStorage). Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      if(localStorageService.isSupported) {
        //...
      }
      //...
    });

    getStorageType

    Returns: String

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      var storageType = localStorageService.getStorageType(); //e.g localStorage
      //...
    });

    You can also dynamically change storage type by passing the storage type as the last parameter for any of the API calls. For example: localStorageService.set(key, val, "sessionStorage");

    set

    Directly adds a value to local storage.
    If local storage is not supported, use cookies instead.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function submit(key, val) {
       return localStorageService.set(key, val);
      }
      //...
    });

    get

    Directly get a value from local storage.
    If local storage is not supported, use cookies instead.
    Returns: value from local storage

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function getItem(key) {
       return localStorageService.get(key);
      }
      //...
    });

    keys

    Return array of keys for local storage, ignore keys that not owned.
    Returns: value from local storage

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      var lsKeys = localStorageService.keys();
      //...
    });

    remove

    Remove an item(s) from local storage by key.
    If local storage is not supported, use cookies instead.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function removeItem(key) {
       return localStorageService.remove(key);
      }
      //...
      function removeItems(key1, key2, key3) {
       return localStorageService.remove(key1, key2, key3);
      }
    });

    clearAll

    Remove all data for this app from local storage.
    If local storage is not supported, use cookies instead.
    Note: Optionally takes a regular expression string and removes matching.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function clearNumbers(key) {
       return localStorageService.clearAll(/^d+$/);
      }
      //...
      function clearAll() {
       return localStorageService.clearAll();
      }
    });

    bind

    Bind $scope key to localStorageService. Usage: localStorageService.bind(scope, property, value[optional], key[optional]) key: The corresponding key used in local storage Returns: deregistration function for this listener.

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      localStorageService.set('property', 'oldValue');
      $scope.unbind = localStorageService.bind($scope, 'property');
    
      //Test Changes
      $scope.update = function(val) {
        $scope.property = val;
        $timeout(function() {
          alert("localStorage value: " + localStorageService.get('property'));
        });
      }
      //...
    });
    <div ng-controller="MainCtrl">
      <p>{{property}}</p>
      <input type="text" ng-model="lsValue"/>
      <button ng-click="update(lsValue)">update</button>
      <button ng-click="unbind()">unbind</button>
    </div>

    deriveKey

    Return the derive key Returns String

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      localStorageService.set('property', 'oldValue');
      //Test Result
      console.log(localStorageService.deriveKey('property')); // ls.property
      //...
    });

    length

    Return localStorageService.length, ignore keys that not owned. Returns Number

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      var lsLength = localStorageService.length(); // e.g: 7
    });

    Cookie

    Deal with browser's cookies directly.

    cookie.isSupported

    Checks if cookies are enabled in the browser. Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      if(localStorageService.cookie.isSupported) { 
      }
      //...
    });

    cookie.set

    Directly adds a value to cookies.
    Note: Typically used as a fallback if local storage is not supported.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function submit(key, val) {
       return localStorageService.cookie.set(key, val);
      }
      //...
    });

    Cookie Expiry Pass a third argument to specify number of days to expiry

        localStorageService.cookie.set(key,val,10)

    sets a cookie that expires in 10 days. Secure Cookie Pass a fourth argument to set the cookie as secure W3C

        localStorageService.cookie.set(key,val,null,false)

    sets a cookie that is secure.

    cookie.get

    Directly get a value from a cookie.
    Returns: value from local storage

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function getItem(key) {
       return localStorageService.cookie.get(key);
      }
      //...
    });

    cookie.remove

    Remove directly value from a cookie.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function removeItem(key) {
       return localStorageService.cookie.remove(key);
      }
      //...
    });

    cookie.clearAll

    Remove all data for this app from cookie.
    Returns: Boolean

    myApp.controller('MainCtrl', function($scope, localStorageService) {
      //...
      function clearAll() {
       return localStorageService.cookie.clearAll();
      }
    });

    Check out the full demo at http://gregpike.net/demos/angular-local-storage/demo.html

    Development:

    • Don't forget about tests.
    • If you're planning to add some feature please create an issue before.

    Clone the project:

    $ git clone https://github.com/<your-repo>/angular-local-storage.git
    $ npm install
    $ bower install

    Run the tests:

    $ grunt test

    Deploy:
    Run the build task, update version before(bower,package)

    $ npm version patch|minor|major
    $ grunt dist
    $ git commit [message]
    $ git push origin master --tags

    //本地缓存操作
    $scope.localSave = app.localSave = function (key,value) {
    localStorageService.set(key,value);
    localStorageService.cookie.set(key,value);

    };
    $scope.localGet = app.localGet = function (key) {
    return localStorageService.get(key) ||
    localStorageService.cookie.get(key);
    };
    $scope.localRemove = app.localRemove = function (key) {
    localStorageService.remove(key);
    localStorageService.cookie.remove(key);
    };
    $scope.urlGet = app.urlGet = function (key) {
    var url_pid=window.location.search.substring(1);
    var pairs = url_pid.split("&");
    var urlinfo={};
    for(var i = 0; i < pairs.length; i++) {
    var pos = pairs[i].indexOf('=');
    urlinfo[pairs[i].substring(0,pos)]=pairs[i].substring(pos+1);
    }
    return urlinfo[key];

    };
    $scope.sessionGet = app.sessionGet = function(key){
    if(window.sessionStorage){
    var item = window.sessionStorage[key];
    if(item){
    return JSON.parse(item);
    }else{
    return item;
    }
    }else{
    return $scope.localGet(key);
    }
    return undefined;
    }
    $scope.sessionSave = app.sessionSave = function(key,value){
    if(window.sessionStorage){
    window.sessionStorage[key] = angular.toJson(value);
    }else{
    $scope.localSave(key,value);
    }
    }
    $scope.sessionRemove = app.sessionRemove = function(key){
    if(window.sessionStorage){
    window.sessionStorage[key] = undefined;
    }else{
    $scope.localRemove(key);
    }
    }
     
  • 相关阅读:
    关于我成为电脑维修社团一员那些事
    [算法相关]二进制分组
    [题解]陌上花开
    [题解]UVA10917 Walk Through the Forest
    [字符串相关]后缀自动机(SAM)- 一
    [字符串相关]后缀数组
    [字符串相关]Aho-Corasick 自动机
    [算法入门]线性基
    [数据结构]可持久化并查集
    [数据结构]可持久化线段树
  • 原文地址:https://www.cnblogs.com/zzcit/p/6289877.html
Copyright © 2020-2023  润新知