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/

相关文章:

javascript - 如何在 <md-radio-group> 中使用输入字段作为自定义条目?

javascript - 在 Canvas 上绘制多个矩形框,不要重叠

javascript - 从 Controller 中为 `<option>` 选择 `<select ng-options>` 值

angularjs - ng-model 和 ng-options 不匹配?

search - angularJS 搜索模型

javascript - npm 错误! 404 未找到 npm 错误!不好 代码 0

AngularJS - 如何在嵌套 http.get 请求的情况下返回对象

javascript - 如果第二个不为空,则 Ng-options 下拉连接字段

javascript - ngOptions 按值比较

javascript - ng-option 过滤器不工作