是否可以通过包含在另一个数组中来过滤 angular.js? [英] Is it possible to filter angular.js by containment in another array?

查看:23
本文介绍了是否可以通过包含在另一个数组中来过滤 angular.js?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以如果我有一个数组:

$scope.letters =[{"id":"a"},{"id":"b"},{"id":"c"}];

另一个数组

$scope.filterBy = ["b","c","d"];

而且我想要一些 ng-repeat 来过滤 $scope.letters 中只出现在 $filterBy 中的项目.

我希望能够做一些事情:

<span ng-repeat="{{字母中的字母|过滤器:filterBy 中的 letter.id }} > {{letter.id}} </span>

并让它打印 b,c

我知道这是一个非常愚蠢的例子,但是有没有办法根据另一个数组对象的内容过滤 angular.js 表达式?

解决方案

你应该尝试这样的事情:

JS:

angular.module('Test', []);功能Ctrl($范围){$scope.letters = [{id: 'a'},{id: 'b'},{id:'c'}];$scope.filterBy = ['b', 'c', 'd'];$scope.filteredLetters = 函数 () {返回 $scope.letters.filter(function (letter) {返回 $scope.filterBy.indexOf(letter.id) !== -1;});};}Ctrl.$inject = ['$scope'];

HTML:

{{letter.id}}</div>

您可以尝试现场示例.

So if I have an array:

$scope.letters = 
[{"id":"a"},
{"id":"b"},
{"id":"c"}];

And another array

$scope.filterBy = ["b","c","d"];

And I want to have some ng-repeat to filter $scope.letters by only items that appear in $filterBy.

I want to be able to do something to the effect of:

<span ng-repeat="{{letter in letters|filter: letter.id in filterBy }} > {{letter.id}} </span>

And have it print b,c

I know this is a really stupid example, but is there a way to filter an angular.js expression based on the contents of another array object?

解决方案

You should try something like that:

JS:

angular.module('Test', []);

function Ctrl($scope) {
  $scope.letters = [
    {id: 'a'},
    {id: 'b'},
    {id: 'c'}
  ];

  $scope.filterBy = ['b', 'c', 'd'];

  $scope.filteredLetters = function () {
    return $scope.letters.filter(function (letter) {
      return $scope.filterBy.indexOf(letter.id) !== -1;
    });
  };
}

Ctrl.$inject = ['$scope'];

HTML:

<div ng-repeat='letter in filteredLetters(letters)'>{{letter.id}}</div>

You can try live example.

这篇关于是否可以通过包含在另一个数组中来过滤 angular.js?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆