【问题标题】:Angular 1.x: Using select & ng-options with a custom filterAngular 1.x:将 select 和 ng-options 与自定义过滤器一起使用
【发布时间】:2016-03-13 04:07:25
【问题描述】:

前言

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

codepen - 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 docs) 的误解,还是在使用带有 &lt;select&gt; 的过滤器而不是其他输入时存在一些微妙之处。

据我了解differenceWith,它旨在比较 2 个数组并利用 comarator 函数,如果要排除它们,则返回 true。过滤器确实有效,但为什么它没有正确呈现ng-model默认值或选择的值?

【问题讨论】:

  • 我认为正确的语法是filter:excludedAttrs:vc.cols
  • 不幸的是,这将需要我的 viewController 上的 excludedAttrs 函数,并且它需要更改以针对当前选择处理单个对象。我正在尝试保持 viewController 的亮度。

标签: angularjs select lodash angular-ngmodel angular-filters


【解决方案1】:

选择未显示当前选定的ng-model 的问题是因为实际的&lt;option/&gt; 不存在于ng-options 中,因为过滤器将其排除在集合中。

为了解决这个问题,我需要排除当前选择的值(即ng-model 被排除在...好吧,我不得不将它重新添加到过滤ng-options

codepen - 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;
        });
    };
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 2011-05-31
    • 2017-02-08
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多