Angular 1.x:将 select & ng-options 与自定义过滤器结合使用



前言

我编写了一个自定义过滤器,从多个<select>输入的可用选项列表中排除当前选定的选项。

代码笔 - http://codepen.io/jusopi/pen/XdjNWa?editors=1010

模板实现

<select class="form-control" ng-model="vc.cols[0].attr" 
    ng-options="opt.attr as opt.name for opt in vc.opts | excludedAttrs:vc.cols">

滤波器

.filter('excludedAttrs', function () {
    return function (opts, cols) {
        return _.differenceWith(opts, cols, function (opt, col) {
            return opt.attr === col.attr;
        });
    };
})

问题所在

我不确定这是否是我对 Lodash differenceWith(API 文档)的误解,还是在使用过滤器时有一些微妙之处,<select>于其他输入。

据我了解differenceWith,它旨在比较 2 个数组,并利用一个比较器函数,如果要排除它们,则返回 true。 过滤器实际上可以工作,但为什么它不能正确呈现ng-model默认值或所选值?

选择未显示当前所选ng-model的问题是因为实际<option/>不在ng-options中,因为筛选器将其排除在集合中。

为了解决这个问题,我需要排除当前选定的值(即ng-model...好吧,不被排除在外。 基本上我不得不将其添加回过滤ng-options.

代码笔 - http://codepen.io/jusopi/pen/XdjNWa?editors=1010

模板实现

<select ng-model="vc.cols[0].attr" 
    ng-options="opt.attr as opt.name for opt in vc.opts | excludedAttrs:vc.cols:0">

固定过滤器

.filter('excludedAttrs', function () {
    return function (opts, cols, i) {
        // fix
        cols = _.without(cols, cols[i]);
        // end fix
        return _.differenceWith(opts, cols, function (opt, col) {
            return opt.attr === col.attr;
        });
    };
})

最新更新