针对本地存储中的列表过滤ng-repeat

时间:2015-01-26 12:53:21

标签: javascript json angularjs local-storage

我'将ID列表存储在本地存储中作为列表,我希望在加载JSON对象时进行过滤,并使用ng-repeat循环遍历此JSON对象中的对象。我的想法是使用ng-repeat显示的任何项目,如果他们的ID在列表中,那么我不想显示它们。

我正在构建通知页面,如果已经读取了消息,那么我将通知的ID存储在本地存储中,这样我就可以跟踪已经读取的通知。然后当我得到一个带有任何新通知的新JSON对象时,我可以检查该JSON对象中哪些已被读取,然后不显示它们。

我不太确定如何使用ng-repeat,任何想法过滤它们?

由于

斯蒂芬

1 个答案:

答案 0 :(得分:1)

var myApp = angular.module("myApp", []);


myApp.controller("myController1", function($scope) {

  $scope.hideblocked = function(blockedIds) {
    return function(item) {
      return blockedIds.indexOf(item.id) == -1;
    }
  }

  $scope.blockedIds = [1, 5];

  $scope.items = [{
    "id": 1,
    "name": "a"
  }, {
    "id": 2,
    "name": "b"
  }, {
    "id": 5,
    "name": "c"
  }, {
    "id": 8,
    "name": "d"
  }, {
    "id": 12,
    "name": "e"
  }, {
    "id": 3,
    "name": "f"
  }];

  $scope.blockedIds2 = ["1", "5"];

  $scope.items2 = [{
    "id": "1",
    "name": "a"
  }, {
    "id": "2",
    "name": "b"
  }, {
    "id": "5",
    "name": "c"
  }, {
    "id": "8",
    "name": "d"
  }, {
    "id": "12",
    "name": "e"
  }, {
    "id": "3",
    "name": "f"
  }];

  $scope.block = function(blockedIds, id) {
    if (blockedIds.indexOf(id) == -1) {
      blockedIds.push(id);
    }

  };


});
<div ng-app="myApp" ng-controller="myController1">
  If id is a number :
  <span ng-repeat="item in items| filter:hideblocked(blockedIds)">{{item.name}}</span>
  <button ng-click="block(blockedIds,3)">block f</button>
  <br/>If id is a string:
  <span ng-repeat="item in items2| filter:hideblocked(blockedIds2)">{{item.name}}</span>
  <button ng-click="block(blockedIds2,'3')">block f</button>
</div>
<script src="https://code.angularjs.org/1.3.8/angular.min.js"></script>