使用角度js过滤器从列表中删除值

时间:2016-05-13 07:36:26

标签: angularjs filter

我是棱角分明的新手。有一些麻烦解决这个问题。

假设我有这个:

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

app.controller('myCtrl', function($scope) {
   $scope.num = ["1", "2", "3","toto","5","6","toto","7"];

});

如何进行迭代以便从列表中删除所有'toto'并返回没有'toto'的数组。我尝试使用过滤器,但它无法正常工作。我怎么能通过使用过滤器来做到这一点?感谢

请帮助。

2 个答案:

答案 0 :(得分:3)

一样使用它
var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) { 

  $scope.num = ["1", "2", "3","toto","5","6","toto","7"];

  $scope.num = $scope.num.filter(function(n){
         return (n != "toto")
   });
  console.log($scope.num)
});

答案 1 :(得分:1)

不确定您是否要使用javascript过滤器功能或角度过滤器。

@sumair向您展示了javascript one,这是使用$filter的角度曲目:

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

app.controller('myCtrl', function($scope, $filter) {
    $scope.num = ["1", "2", "3", "toto", "5", "6", "toto", "7"];

    $scope.num = $filter('filter')($scope.num, function(item) {
        return item !== 'toto';
    });
});

您可能希望隔离传递给$ filter的函数,以便您可以直接从html使用它来更改视图而无需触及模型:

JS:

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

app.controller('myCtrl', function($scope) { 

  $scope.num = ["1", "2", "3","toto","5","6","toto","7"];

  $scope.filterCriteria = function(item) {
      return item != 'toto';
  };
});

HTML:

<ul>
    <li ng-repeat="item in num | filter:filterCriteria" ng-bind="item"></li>
</ul>