Angular 1.6 - ng-if 当数组中的元素是另一个对象中的键时



在Angular中,我有一个这样的数组:

$scope.items =["blue","red","pink","yellow"];

还有另一个对象(我用于过滤(

$scope.filter={"color":{"blue":true, "pink":true},"shape":{"square":true}};

我想做一个ng-if,以便

<ul>
    <li ng-repeat="n in items" ng-if="n in filter.color">
    </li>
</ul>

ng-repeat将只显示$scope.items中存在的元素$scope.filter

所以,换句话说,它只会显示蓝色粉红色

提前感谢!

您需要一个自定义过滤器函数:

<ul>
    <li ng-repeat="n in items | filter: yourFilter">
    </li>
</ul>
$scope.filter={"color":{"blue":true, "pink":true},"shape":{"square":true}};
$scope.yourFilter = function(item) {
  //will be true when color has a property with the color and it's true
  return $scope.filter.color[item];
}

由于 $scope.items 是一个数组,而 $scope.filter 是一个对象,因此您需要一个函数来测试值:

angular.module('test', []).controller('testController', function($scope)
  {
  $scope.items =["blue","red","pink","yellow"];
  $scope.filter={"color":{"blue":true, "pink":true}};
  
  $scope.checkColor = function(value, index, array)
    {
    return $scope.filter.color[value];
    };
  });
  
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="test">
<div ng-controller="testController">
<ul>
    <li ng-repeat="n in items | filter : checkColor">{{n}}</li>
</ul>
</div>
</body>

相关内容

最新更新