如何将按钮值存储在本地存储语言中?

时间:2018-06-21 07:37:40

标签: javascript jquery html local-storage session-state

我正在将angularjs与智能表一起使用,我正在做的是,添加了可扩展和折叠表行的切换按钮,单击一次按钮后,行将展开,如果我重新加载页面,则所有行都将折叠,因为页面重新加载。我希望即使在页面重新加载后也应打开那些行,我该如何实现?

我如何将Button值存储在本地存储中?那么页面重新加载后的按钮状态保持不变吗?

var myApp = angular.module('myApp', [])
  .filter("groupBy", ["$parse", "$filter", function($parse, $filter) {
    return function(array, groupByField) {
      var result = [];
      var prev_item = null;
      var groupKey = false;
      var filteredData = $filter('orderBy')(array, groupByField);
      for (var i = 0; i < filteredData.length; i++) {
        groupKey = false;
        if (prev_item !== null) {
          if (prev_item[groupByField] !== filteredData[i][groupByField]) {
            groupKey = true;
          }
        } else {
          groupKey = true;
        }
        if (groupKey) {
          filteredData[i]['group_by_key'] = true;
        } else {
          filteredData[i]['group_by_key'] = false;
        }
        result.push(filteredData[i]);
        prev_item = filteredData[i];
      }
      return result;
    }
  }])
  .controller('employeeController', function($scope) {

    var employees = [{
      "Name": "Alfreds Futterkiste",
      "City": "Berlin",
      "Country": "Germany"
    }, {
      "Name": "Berglunds snabbköp",
      "City": "Luleå",
      "Country": "Sweden"
    }, {
      "Name": "Blauer See Delikatessen",
      "City": "Mannheim",
      "Country": "Germany"
    }, {
      "Name": "Blondel père et fils",
      "City": "Strasbourg",
      "Country": "France"
    }, {
      "Name": "Bólido Comidas preparadas",
      "City": "Madrid",
      "Country": "Spain"
    }, {
      "Name": "Bon app'",
      "City": "Marseille",
      "Country": "France"
    }, {
      "Name": "Bottom-Dollar Marketse",
      "City": "Tsawassen",
      "Country": "Canada"
    }, {
      "Name": "Cactus Comidas para llevar",
      "City": "Buenos Aires",
      "Country": "Argentina"
    }, {
      "Name": "Centro comercial Moctezuma",
      "City": "México D.F.",
      "Country": "Mexico"
    }, {
      "Name": "Chop-suey Chinese",
      "City": "Bern",
      "Country": "Switzerland"
    }, {
      "Name": "Comércio Mineiro",
      "City": "São Paulo",
      "Country": "Brazil"
    }];
    $scope.employees = employees;

    $scope.IsAllCollapsed = false;
    $scope.collapseAll = function() {
      $scope.IsAllCollapsed = !$scope.IsAllCollapsed;
      $scope.employees.forEach(function(item) {
        item.isCollapsed = $scope.IsAllCollapsed;
      })
    }
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


<body ng-app="myApp">
  <div ng-controller="employeeController">
    <div class="container" style="margin-top:40px;">
      <div class="row">
        <div class="col-md-6">
          <button id="btnExpandAll" type="button" ng-click="collapseAll()" class="btn btn-info" style="margin-left: 0px; margin-bottom: 20px; float: left;">
                                        <span ng-show="IsAllCollapsed"><i class="fa fa-compress" aria-hidden="true"></i>&nbsp;Collapse All</span>
                                        <span ng-show="!IsAllCollapsed"><i class="fa fa-expand" aria-hidden="true"></i>&nbsp; Expand by Country</span>
                                    </button>

          <table class="table table-bordered table-condensed">
            <thead>
              <tr>
                <th>Name</th>
                <th>City</th>
                <th>Country</th>
              </tr>
            </thead>
            <tbody>
              <tr ng-repeat-start="emp in employees |  groupBy:'Country'" ng-show="emp.group_by_key">
                <td colspan="3" ng-if="emp.isCollapsed" ng-click="emp.isCollapsed = false" style="text-align: center; background-color: #eee"><b><span>{{emp.Country}}</span></b></td>
              </tr>

              <tr>

                <td>{{emp.Name}}</td>
                <td>{{emp.City}}</td>
                <td>{{emp.Country}}</td>
              </tr>
              <tr ng-repeat-end=""></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</body>

2 个答案:

答案 0 :(得分:1)

使用以下方法将值设置为本地存储:

localStorage.setItem('buttonInfo', JSON.stringify($scope.IsAllCollapsed));

然后读取值并设置$scope.IsAllCollapsed

$scope.IsAllCollapsed = JSON.parse(localStorage.getItem("buttonInfo"));

请在您的本地PC环境中进行测试。出于安全原因,它不适用于stackoverflow:

有效的代码段在这里:

var myApp = angular.module('myApp', [])
  .filter("groupBy", ["$parse", "$filter", function($parse, $filter) {
    return function(array, groupByField) {
      var result = [];
      var prev_item = null;
      var groupKey = false;
      var filteredData = $filter('orderBy')(array, groupByField);
      for (var i = 0; i < filteredData.length; i++) {
        groupKey = false;
        if (prev_item !== null) {
          if (prev_item[groupByField] !== filteredData[i][groupByField]) {
            groupKey = true;
          }
        } else {
          groupKey = true;
        }
        if (groupKey) {
          filteredData[i]['group_by_key'] = true;
        } else {
          filteredData[i]['group_by_key'] = false;
        }
        result.push(filteredData[i]);
        prev_item = filteredData[i];
      }
      return result;
    }
  }])
  .controller('employeeController', function($scope, $rootScope) {

    var employees = [{
      "Name": "Alfreds Futterkiste",
      "City": "Berlin",
      "Country": "Germany"
    }, {
      "Name": "Berglunds snabbköp",
      "City": "Luleå",
      "Country": "Sweden"
    }, {
      "Name": "Blauer See Delikatessen",
      "City": "Mannheim",
      "Country": "Germany"
    }, {
      "Name": "Blondel père et fils",
      "City": "Strasbourg",
      "Country": "France"
    }, {
      "Name": "Bólido Comidas preparadas",
      "City": "Madrid",
      "Country": "Spain"
    }, {
      "Name": "Bon app'",
      "City": "Marseille",
      "Country": "France"
    }, {
      "Name": "Bottom-Dollar Marketse",
      "City": "Tsawassen",
      "Country": "Canada"
    }, {
      "Name": "Cactus Comidas para llevar",
      "City": "Buenos Aires",
      "Country": "Argentina"
    }, {
      "Name": "Centro comercial Moctezuma",
      "City": "México D.F.",
      "Country": "Mexico"
    }, {
      "Name": "Chop-suey Chinese",
      "City": "Bern",
      "Country": "Switzerland"
    }, {
      "Name": "Comércio Mineiro",
      "City": "São Paulo",
      "Country": "Brazil"
    }];
    $scope.employees = employees;
   
    $scope.IsAllCollapsed = JSON.parse(localStorage.getItem("buttonInfo")) ? JSON.parse(localStorage.getItem("buttonInfo")): false;

    $scope.employees.forEach(function(item) {
        item.isCollapsed = $scope.IsAllCollapsed;
    });

    $scope.collapseAll = function() {

      $scope.IsAllCollapsed = !$scope.IsAllCollapsed;
      localStorage.setItem('buttonInfo', JSON.stringify($scope.IsAllCollapsed));
      $scope.employees.forEach(function(item) {
        item.isCollapsed = $scope.IsAllCollapsed;
      })
    }
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<script src="app.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


<body ng-app="myApp">
  <div ng-controller="employeeController">
    <div class="container" style="margin-top:40px;">
      <div class="row">
        <div class="col-md-6">
          <button id="btnExpandAll" type="button" ng-click="collapseAll()" class="btn btn-info" style="margin-left: 0px; margin-bottom: 20px; float: left;">
                                        <span ng-show="IsAllCollapsed"><i class="fa fa-compress" aria-hidden="true"></i>&nbsp;Collapse All</span>
                                        <span ng-show="!IsAllCollapsed"><i class="fa fa-expand" aria-hidden="true"></i>&nbsp; Expand by Country</span>
                                    </button>

          <table class="table table-bordered table-condensed">
            <thead>
              <tr>
                <th>Name</th>
                <th>City</th>
                <th>Country</th>
              </tr>
            </thead>
            <tbody>
              <tr ng-repeat-start="emp in employees |  groupBy:'Country'" ng-show="emp.group_by_key">
                <td colspan="3" ng-if="emp.isCollapsed" ng-click="emp.isCollapsed = false" style="text-align: center; background-color: #eee"><b><span>{{emp.Country}}</span></b></td>
              </tr>

              <tr>

                <td>{{emp.Name}}</td>
                <td>{{emp.City}}</td>
                <td>{{emp.Country}}</td>
              </tr>
              <tr ng-repeat-end=""></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</body>

答案 1 :(得分:1)

我找到了解决方案,我已经使用了ngStorage ngStorage  为此

  angular.module('App', ['ngStorage'])
     .controller('employeeController', function ($scope,$localStorage) {
})

OnPageLoad:

$scope.IsAllCollapsed = ($localStorage.IsAllCollapsed == undefined) ? $scope.IsAllCollapsed : $localStorage.IsAllCollapsed;

全局变量:

$scope.IsAllCollapsed = false;

在功能内;

      BindCollapseToData($scope.employees);
                                  $scope.collapseAll = function () {
                                      $scope.IsAllCollapsed = !$scope.IsAllCollapsed;
                                      $localStorage.IsAllCollapsed = $scope.IsAllCollapsed;
                                      BindCollapseToData($scope.employees);
                                  }

外部功能:

    function BindCollapseToData(DataColl) {
                           DataColl.forEach(function (item) {
                               item.isCollapsed = $scope.IsAllCollapsed;
                           })
                       }