AngularJS:使用本地存储 [英] AngularJS : use local storage

查看:71
本文介绍了AngularJS:使用本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Web数据保存在本地存储中.我有一个表,可以向其中添加数据,它可以与AngularJS一起使用.我想要保存数据,该怎么办?

I want to save my web data in the local storage. I have a table which I add to it data, it works with AngularJS. I would like the data to be saved, how do I do it ?

代码: html代码:

the code : the html code :

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

推荐答案

AngularJS服务: 直接使用window.localStorage很好,但是过一会儿不得不设置和解析Strings会很麻烦.使用此简单的AngularJS服务可轻松设置和检索字符串或对象:

AngularJS Service: Using window.localStorage directly is just fine, but having to set and parse Strings gets tiresome after a while. Use this simple AngularJS service for setting and retrieving strings or objects easily:

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服务注入到控制器或运行函数中即可:

And to use this service, just inject the $localstorage service into a controller or run function:

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

这篇关于AngularJS:使用本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆