AngularJS:使用本地存储

时间:2015-09-09 18:34:56

标签: angularjs local-storage

我想将我的网页数据保存在本地存储中。我有一个表,我添加到它的数据,它与AngularJS一起使用。我想保存数据,我该怎么办?

代码: HTML代码:

<!doctype html>
<html ng-app="ui.bootstrap.demo">

<head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.13.3.js"></script>
    <script src="app.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>

<div ng-controller="AppCtrl" >
    <button type="button" class="btn btn-default" ng-click="openR()"> add user </button>
    <button type="button" class="btn btn-default" ng-click="openC()"> connect </button>
    <div class="btn btn-success" ng-show="User.connected">{{User.username}} is connected</div>
    <table>
        <thead>
        <th class="col-lg-3">Username</th>
        <th class="col-lg-3">Password</th>
        <th class="col-lg-3">First name</th>
        <th class="col-lg-3">Last name</th>
        </thead>
        <tbody>
        <tr ng-repeat="User in Users.slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage))">
            <td class="col-lg-3">{{User.userN}}</td>
            <td class="col-lg-3">{{User.PassW}}</td>
            <td class="col-lg-3">{{User.Name}}</td>
            <td class="col-lg-3">{{User.LastName}}</td>
        </tr>
        </tbody>
    </table>
    <div>
        <pagination total-items="totalItems" ng-model="currentPage" max-size="maxSize" class="pagination-sm" boundary-links="true" rotate="false" num-pages="numPages" items-per-page="itemsPerPage"></pagination>
    </div>
</div>
<script type="text/ng-template" id="table.html">
    <form ng-submit="okR()">
        <div class="modal-header" >
            <h3>users</h3>
        </div>
        <div class="modal-body">
            <div class="panel-body">
                <div class="form-group">
                    <label>Username :</label>
                    <input type="text" placeholder="Ariel73" ng-model="userN">
                </div>
                <div class="form-group">
                    <label>Password :</label>
                    <input type="text" placeholder="Aa123456" ng-model="PassW">
                </div>
                <div class="form-group">
                    <label>First name :</label>
                    <input type="text" placeholder="Ariel" ng-model="Name">
                </div>
                <div class="form-group">
                    <label>Last name :</label>
                    <input type="text" placeholder="Livshits" ng-model="LastName">
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit"  class="btn btn-success">Submit</button>
            </div>
        </div>
    </form>
</script>
<script type="text/ng-template" id="connect.html">
    <form ng-submit="okC()">
        <div class="modal-header" >
            <h3>users</h3>
        </div>
        <div class="modal-body">
            <div class="panel-body">
                <div class="form-group">
                    <label>Username :</label>
                    <input type="text" placeholder="Ariel73" ng-model="username">
                </div>
                <div class="form-group">
                    <label>Password :</label>
                    <input type="text" placeholder="Aa123456" ng-model="password">
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit"  class="btn btn-success">Submit</button>
            </div>
        </div>
    </form>
</script>
</body>

</html>

角度应用代码:

app = angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']);
app.controller('AppCtrl', function($scope, $modal, $log ) {
    $scope.Users = [{
        'userN': 'Ariel1',
        'PassW': 'Aa123456',
        'Name': 'Ariel',
        'LastName': 'Livshits'
    }, {
        'userN': 'Ariel2',
        'PassW': 'Aa123456',
        'Name': 'Ariel',
        'LastName': 'Livshits'
    }, {
        'userN': 'Ariel3',
        'PassW': 'Aa123456',
        'Name': 'Ariel',
        'LastName': 'Livshits'
    }, {
        'userN': 'Ariel4',
        'PassW': 'Aa123456',
        'Name': 'Ariel',
        'LastName': 'Livshits'
    }, {
        'userN': 'Ariel5',
        'PassW': 'Aa123456',
        'Name': 'Ariel',
        'LastName': 'Livshits'
    }, {
        'userN': 'Ariel6',
        'PassW': 'Aa123456',
        'Name': 'Ariel',
        'LastName': 'Livshits'
    }, {
        'userN': 'Ariel6',
        'PassW': 'Aa123456',
        'Name': 'Ariel',
        'LastName': 'Livshits'
    }, {
        'userN': 'Ariel6',
        'PassW': 'Aa123456',
        'Name': 'Ariel',
        'LastName': 'Livshits'
    }];

    $scope.User = {
        'username': '',
        'Password': '',
        'connected': false
    };
    $scope.viewby = 3;
    $scope.totalItems = $scope.Users.length;
    $scope.currentPage = 4;
    $scope.itemsPerPage = $scope.viewby;
    $scope.maxSize = (($scope.Users.length / 3) + 1) ; //Number of pager buttons to show

    $scope.setPage = function (pageNo) {
        $scope.currentPage = pageNo;
    };

    $scope.pageChanged = function() {
        console.log('Page changed to: ' + $scope.currentPage);
    };

    $scope.setItemsPerPage = function(num) {
        $scope.itemsPerPage = num;
        $scope.currentPage = 1; //reset to first paghe
    };


    $scope.openR = function() {

        var modalInstance = $modal.open({
            templateUrl: 'table.html',
            controller: 'ModalInstanceCtrl'
        });
        modalInstance.result.then(function(newUser) {
            $scope.Users.push(newUser);
        }, function() {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.openC = function() {

        var modalInstance = $modal.open({
            templateUrl: 'connect.html',
            controller: 'ModalInstanceCtrl'
        });
        modalInstance.result.then(function(conUser) {
            $scope.User = conUser;
        }, function() {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
});

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

app.controller('ModalInstanceCtrl', function($scope, $modalInstance) {
    $scope.okR = function() {
        $modalInstance.close({
            'userN': $scope.userN,
            'PassW': $scope.PassW,
            'Name': $scope.Name,
            'LastName': $scope.LastName
        });
    };

    $scope.okC = function() {
        $modalInstance.close({
            'username': $scope.username,
            'Password': $scope.password,
            'connected': true
        });
    };

    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
});

3 个答案:

答案 0 :(得分:12)

AngularJS服务: 直接使用window.localStorage就好了,但是一段时间后不得不设置和解析字符串会很烦人。使用这个简单的AngularJS服务可以轻松设置和检索字符串或对象:

angular.module('ionic.utils', [])

.factory('$localstorage', ['$window', function($window) {
  return {
    set: function(key, value) {
      $window.localStorage[key] = value;
    },
    get: function(key, defaultValue) {
      return $window.localStorage[key] || defaultValue;
    },
    setObject: function(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key) {
      return JSON.parse($window.localStorage[key] || '{}');
    }
  }
}]);

要使用此服务,只需将$ localstorage服务注入控制器或运行函数:

angular.module('app', ['ionic', 'ionic.utils'])

.run(function($localstorage) {

  $localstorage.set('name', 'Max');
  console.log($localstorage.get('name'));
  $localstorage.setObject('post', {
    name: 'Thoughts',
    text: 'Today was a good day'
  });

  var post = $localstorage.getObject('post');
  console.log(post);
});

答案 1 :(得分:0)

在模态中使用ng-model =“newUser.userN”,ng-model =“newUser.PassW”代替ng-model =“userN”,ng-model =“PassW”等。

然后创建一个这样的方法:

$scope.saveNewUser = function(newUser) { window.localStorage.setItem("newUser", JSON.stringify(newUser)}

并将提交操作更改为此功能。

如果要将表数据保存到localstorage:

$scope.saveUsers = function() {window.localStorage.setItem("tableData", JSON.stringify($scope.Users));}

答案 2 :(得分:0)

除了使用和添加localstorage作为依赖之外,您可以在任何想要获得本地存储的控制器中注入$window依赖关系,并且它不需要安装任何东西,你只需要这样做< / p>

对于设置,你可以像

一样
window.localStorage.setItem('key', 'value' );

为了获得,你可以像

一样
window.localStorage.getItem('key');

如果您想显示该值,您可以将其包装在范围内并将其绑定到html中,如下所示

$scope.displayThis = window.localStorage.getItem('key');

然后你可以在控制器的html表示中显示它,如下所示:

<span>{{displayThis}}</span>