angularjs - ng-options 中的过滤器不起作用

标签 angularjs ng-options

我有一个将 ID 映射到其对象的对象。我想显示这些对象的列表并使用过滤器,但我无法让它工作。具体来说,我试图阻止 ID 为 2 的对象出现在选项中,这是我得到的: 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>

请注意:我无法在我们提出的任何修复中更改 bidTypes 对象的结构。这是我的 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"}
    };
}

最佳答案

documentation所述, filter 过滤器仅接受数组作为第一个参数,而不是对象。在这种情况下,我个人使用自定义过滤器来进行转换:

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

                    return array;
                };
            }
        ]
    )
;

然后,在模板中:

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

关于angularjs - ng-options 中的过滤器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23703514/

相关文章:

angularjs - 如何使用 Sinon 测试在 promise 中设置的 AngularJS Controller 值

javascript - Protractor 找不到 Angular

javascript - AngularJS:ng-options "non-choice"不是顶部

javascript - select with ngOptions 选择另一个数组的过滤器

javascript - 在 ng-repeat 中获取 Firebase 对象名称值

javascript - 在 `$scope.eventSource` 上,属性 `className` 不相加 - 问题

javascript - 如何强制更新 ng-init ?

javascript - AngularJS:ng-model 将 int 转换为字符串

javascript - angularjs ng-option 空白选项改为预选

javascript - AngularJS 1.4.8 - 选择中的 ngOptions - 当我在 ngOptions 中的选项之前以编程方式设置模型时无限 $digest() 循环