在本地存储中创建javascript数组和变量 - AngularJS

时间:2014-02-21 06:14:20

标签: javascript angularjs

任何人都可以告诉我如何使用angularJS在localstorage中创建像myarray = []这样的数组以及其他变量, 我创建了变量,如下所示。

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <script data-require="angular.js@1.1.5" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>

    <script>
      angular.module('app', [
        'ngStorage'
      ]).

      controller('Ctrl', function(
        $scope,
        $localStorage
      ){
        $scope.$storage = $localStorage.$default({
          x: 42  // variable
        });
      });
    </script>
  </head>

  <body ng-controller="Ctrl">
    <button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button> + <button ng-click="$storage.y = $storage.y + 1">{{$storage.y}}</button> = {{$storage.x + $storage.y}}
  </body>

</html>

1 个答案:

答案 0 :(得分:1)

它支持json,你可以存储JSON不支持的任何东西:

Demo

<script>
      angular.module('app', [
        'ngStorage'
      ]).

      controller('Ctrl', function(
        $scope,
        $localStorage
      ){
        $scope.$storage = $localStorage.$default({
          x: 42,
          array:[]
        });
      });
    </script>