Filter in ng-options not working

谁说胖子不能爱 提交于 2019-12-14 02:14:46

问题


I have an object that maps IDs to their objects. I would like to display the list of these object and use a filter, but I cannot get it to work. Specifically, I'm trying to prevent object with ID 2 from appearing in the options Here's what I've got: http://jsfiddle.net/9d2Za/

<div ng-app ng-controller="ctrl">
    Unfiltered:
    <select ng-model="selectedBidType"
        ng-options="bidType.id as bidType.label for (bidTypeID, bidType) in bidTypes">

    </select>
    <br>
    Filtered:
    <select ng-model="selectedBidType"
        ng-options="bidType.id as bidType.label for (bidTypeID, bidType) in bidTypes | filter:{id: '!2'}">

    </select>
</div>

Please note: I cannot change the structure of the bidTypes object in whatever fix we come up with. Here's my AngularJS:

function ctrl($scope)
{
    $scope.selectedBidType = 1;
    // Bid type objects are indexed by ID for fast lookup (this cannot be changed in solution)
    $scope.bidTypes = {
        1: {id: 1, label: "Buy"},
        2: {id: 2, label: "Sell"},
        3: {id: 3, label: "Missing"}
    };
}

回答1:


As described by the documentation, the filter filter only accepts an array as first parameter, not an object. In such cases, I personally use a custom filter to make the transformation:

myModule.filter(
        'objectToArray',
        [
            function ()
            {
                return function (object)
                {
                    var array = [];
                    angular.forEach(object, function (element)
                    {
                        array.push(element);
                    });

                    return array;
                };
            }
        ]
    )
;

And then, in the template:

 <select ng-options="… in bidTypes | objectToArray | filter:{id:'!2'}">


来源:https://stackoverflow.com/questions/23703514/filter-in-ng-options-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!