angularJS - 如何仅按对象中的一项进行过滤

angularJS - How to filter by one item in object only

在此 JSFiddle (https://jsfiddle.net/eug0taf9/9/) 中,我 select 评分并希望显示图像。

发生了什么事?

当我 select 评价 'High' 时,显示了 2 张图像而不是 1 张,因为过滤器正在捕获类别 'High' 以及类别中图像的描述 'High' 'Low'.

我期望发生什么?

关于 select 评分 "High",我只想过滤类别。我也不需要按描述过滤它。

关于如何解决这个问题有什么建议吗?

HTML代码:

<div ng-app="myApp" ng-controller="myCtrl">
    <span>Select a rating</span>
    <select ng-model="catselect"
            ng-options="category for category in imageCategories"
            ng-change="valueSelected(catselect)">
        <option value>All</option>
    </select>
    <!--<p>Select <input ng-model="categories"/></p>-->

    <ul class="photosmenu">
        <li ng-repeat="image in images | filter : catselect" ng-click="setCurrentImage(image)">
            <img ng-src="{{image.image}}" alt="{{image.stars}}" width="300px"/>
        </li>
    </ul><!-- End of List -->
</div>

Angular代码:

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

mod.controller("myCtrl", function($scope){
    $scope.images = [
        {category: 'High', image: 'img/1.png', description: 'Random Photo', stars: '4/5'},
        {category: 'Medium', image: 'img/6.png', description: 'ApplePhoto', stars: '3/5'},
        {category: 'Low', image: 'img/13.png', description: 'High Top Photo', stars: '2/5'},
        {category: 'None', image: 'img/16.png', description: 'Kilt Photo', stars: '0/5'}];

    $scope.currentImage = $scope.images[0];
    $scope.imageCategories = ["High", "Medium", "Low", "None"];

    $scope.valueSelected = function (value) {

        if (value === null) {
            $scope.catselect = undefined;
        }
    };    

});

这是因为您有一个全局匹配过滤器,它将匹配所有属性,如果您想过滤特定 属性,请相应地设置您的过滤器对象。即

<li ng-repeat="image in images | filter :{category: catselect}"

Demo

或者你也可以将你的 ng-model 设置为一个对象,

<select ng-model="catselect.category"

并做:

<li ng-repeat="image in images | filter :catselect"

Demo

查看 documentation:

string: The string is used for matching against the contents of the array. All strings or objects with string properties in array that match this string will be returned. This also applies to nested object properties. The predicate can be negated by prefixing the string with !.

Object: A pattern object can be used to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1". A special property name $ can be used (as in {$:"text"}) to accept a match against any property of the object or its nested object properties. That's equivalent to the simple substring match with a string as described above. The predicate can be negated by prefixing the string with !. For example {name: "!M"} predicate will return an array of items which have property name not containing "M".