Angular.js:使用$ filter过滤数组

时间:2019-03-05 07:51:11

标签: angularjs

我想做:

myList.forEach(function(element){
   if (!['state1', 'state2'].contains(element.state)){
     myFilteredList.push(element)
   }
})

使用$ filter('filter')以一种优雅的方式,但是我不知道该怎么做。 如果有人知道...

谢谢

2 个答案:

答案 0 :(得分:1)

以下将返回不包含状态1和状态2的对象

myList = [{ state: 'state1', p: 'csss' }, { state: 'state2', p: 'cppss' }, { state: 'state2', p: 'csssss' }, { state: 's1', p: 'csaas' }]
myFilteredList = [];
x = $filter('filter')(myList, (item) => {
    return !['state1', 'state2'].includes(item.state)
})
myFilteredList.push(x)
console.log(myFilteredList);

答案 1 :(得分:1)

您可以使用:

myFilteredList = $filter('filter')(myList, function(element){
    return ['state1', 'state2'].indexOf(element.state) == -1
})

angular.module("app", [])
  .controller("ctrl", function($scope, $filter) {
    var myList = [{
        state: 'state1',
        prop: 'prop1'
      },
      {
        state: 'state2',
        prop: 'prop2'
      },
      {
        state: 'state2',
        prop: 'prop3'
      },
      {
        state: 'state3',
        prop: 'prop4'
      },
      {
        state: 'state4',
        prop: 'prop5'
      }
    ]

    $scope.myFilteredList = $filter('filter')(myList, function(element) {
      return ['state1', 'state2'].indexOf(element.state) == -1
    })
  })
<!DOCTYPE html>
<html ng-app="app">

<head>
</head>

<body ng-controller="ctrl">
  <pre>{{ myFilteredList | json }}</pre>
  <script src="https://code.angularjs.org/1.6.4/angular.min.js"></script>
</body>

</html>