簡體   English   中英

如何在angular中添加本地存儲?

[英]How to add local storage in angular?

我用角做了一張桌子,現在一切都很好。 現在,我想添加本地存儲功能。 我確實盡力做到這一點,但到了現在我不該做什么。 我嘗試使用gsklee / ngStoragegregory / angular-local-storage庫,但是在將其實現到當前代碼時遇到問題。

有人可以看看嗎? 感謝您的時間。

script.js

(function() {
"use strict";

 var table = angular.module('myTable', ['angularUtils.directives.dirPagination','ngStorage']); 

table.filter('startFrom', function() {
    return function(input, start) {
        if(input) {
            start = +start;
        return input.slice(start);
        }
        return [];
    }
});

    table.controller('TodoCtrl', function($scope, $http, $localStorage) {
    $http.get('todos.json').then(function(res) {
        $scope.todos = res.data;
    });

    $scope.currentPage = 1; 
    $scope.entryLimit = 5;

    $scope.sort = function (keyname) {
        $scope.sortKey = keyname;
        $scope.reverse = !$scope.reverse;
    };  

    $scope.DeveloperDelete = function (id){
        var result = confirm('Are you sure?');
        if (result === true) {  
            var index = getSelectedIndex(id);
            $scope.todos.splice(index, 1);
        };
    };

    function getSelectedIndex(id){
        for(var i = 0; i < $scope.todos.length; i++)
            if($scope.todos[i].id == id)
                return i;
            return -1;  
    };

    $scope.addDeveloperRow = function(){        
        $scope.todos.push({ 'id':$scope.id, 'text': $scope.text, 'color':$scope.color, "progress:":$scope.progress});
        $scope.id='';
        $scope.text='';
        $scope.color='';
        $scope.progress='';
    };  

}); 


})();

index.html

<!doctype html>
<html ng-app="myTable" >
<head>
<link rel="stylesheet" type="text/css" href="css/main.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
<script src="dirPagination.js"></script>
<script src="ngStorage.js"></script>

</head>

<body ng-controller="TodoCtrl">

<div class="container">
  <div class="col-lg-12">
      <div>
        <h1 class="centered">My todo list</h1>
      </div>

      <div class="col-lg-3">
        <h4>Search</h4>
        <form>
          <div class="form-group">
            <div class="input-group">
              <div class="input-group-addon"><i class="fa fa-search"></i></div>
              <input type="text" class="form-control" ng-model="test">
            </div>      
          </div>
        </form>
      </div>

      <div class="col-lg-3">   
      <h4>Show number of records</h4>
        <form>
          <div class="form-group">
            <div class="input-group">
              <div class="input-group-addon"><i class="fa fa-search" ></i></div>
                <select ng-model="entryLimit" class="form-control">
                <option>5</option>
                <option>10</option>
                <option>20</option>
                <option>50</option>
                </select>
            </div>      
          </div>
        </form>
      </div>

      <div class="col-lg-3">   
        <h4>Show custom table</h4>
          <form>
            <div class="form-group">
              <div class="input-group">    
                <div class="input-group-addon"><i class="fa fa-search" ></i></div>
                  <select class="form-control ">
                    <option class="btn-sm ng-scope" ng-click="removeId = !removeId" > Hide Id field</option>
                    <option class="btn-sm ng-scope" ng-click="removeText = !removeText" >Hide Text field</option>
                    <option class="btn-sm ng-scope" ng-click="removeColor = !removeColor" >Hide Color field</option>
                    <option class="btn-sm ng-scope" ng-click="removeProgress = !removeProgress" >Hide Progress field</option>             
                  </select>
              </div>      
            </div>
          </form>
      </div>

      <div class="col-lg-3">
      <br><br>
        <form>
          <div class="form-group">
            <div class="input-group">
              <button type="button" class="btn btn-default btn-block " ng-click="addDeveloperRow()">Add a new record</button>
            </div>      
          </div>
        </form>
      </div>


      <br> 
      <table class="table table-striped" st-table="data">
          <thead>
            <th ng-click="sort('id')" ng-hide="removeId" st-sort="id">Id
              <span class="glyphicon sort-icon" ng-show="sortKey=='id'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
            </th>
            <th ng-click="sort('text')" ng-hide="removeText" st-sort="text">Text
              <span class="glyphicon sort-icon" ng-show="sortKey=='text'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
            </th>
            <th ng-click="sort('color')" ng-hide="removeColor" st-sort="color"> Color
              <span class="glyphicon sort-icon" ng-show="sortKey=='color'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
            </th>
            <th ng-click="sort('progress')" ng-hide="removeProgress" st-sort="progress">Progress
              <span class="glyphicon sort-icon" ng-show="sortKey=='color'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span>
            </th>
            <th>CRUD</th>
          </thead>  
          <tbody>
            <tr dir-paginate="todo in todos |orderBy:sortKey:reverse|filter:test| startFrom:(currentPage-1)*entryLimit | itemsPerPage:entryLimit ">
              <td ng-hide="removeId">
                <div ng-hide="todo.editing">{{ todo.id }} </div>

                <div ng-show="todo.editing"><input type="id" ng-model="todo.id" /></div>
              </td>

              <td ng-hide="removeText">                
                <div ng-hide="todo.editing">{{ todo.text }}</div>
                <div ng-show="todo.editing"><input type="text" ng-model="todo.text" /></div>
              </td>
              <td ng-hide="removeColor" style="color:{{todo.color}}" >
                <div ng-hide="todo.editing">{{todo.color}}</div>
                <div ng-show="todo.editing"><input type="text" ng-model="todo.color" /></div>
              </td>
              <td ng-hide="removeProgress">
                <div ng-hide="todo.editing">{{todo.progress}}% </div>
                <div ng-show="todo.editing"><input type="text" ng-model="todo.progress" /></div>
              </td>
              <td>
                <button class="btn btn-danger btn-sm ng-scope"  ng-click="DeveloperDelete(todo.id)"><span class="glyphicon glyphicon-trash"></span></button>
                <button class="btn btn-warning btn-sm ng-scope" ng-click="todo.editing = !todo.editing"><span class="glyphicon glyphicon-pencil"></span></button>
              </td>
            </tr>
          </tbody>
      </table>

     <div class="centeredPag">
      <dir-pagination-controls
        max-size="5"
        direction-links="true"
        boundary-links="true" >
      </dir-pagination-controls>
    </div> 



  </div>
</div>

</body>
</html>

看看我為處理本地存儲所做的此實現。 這確實很簡單,並且實際上不需要任何第三方庫。

(function() {
    'use strict';
    angular.module('myApp')
        .service('LocalStorageService', [
            '$window', function($window) {
                var service = {
                    store: store,
                    retrieve: retrieve,
                    clear: clear,
                    clearAll: clearAll
                };

                return service;

                function store(key, value) {
                    $window.localStorage.setItem(key, angular.toJson(value, false));
                }

                function retrieve(key) {
                    return $window.localStorage.getItem(key);
                    // return angular.fromJson($window.localStorage.getItem(key));
                    // I'm not 100% sure, but I think I need to de-serialize the json that was stored
                }

                function clear(key) {
                    $window.localStorage.removeItem(key);
                }


                function clearAll() {
                    $window.localStorage.clear();
                }


            }
        ]);
})();

如果要使用它,只需要將其注入控制器中,然后開始使用它。

例如:

table.controller('TodoCtrl', function($scope, $http, LocalStorageService) {
    $scope.todos = LocalStorageService.retrieve('todos');
    if (!$scope.todos){    // if 'todos' was not previously stored, $scope.todos will be null
        $http.get('todos.json').then(function(res) {
            $scope.todos = res.data;
            LocalStorageService.store('todos', $scope.todos);
        });
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM