AngularJS 不区分大小写绑定到静态选择下拉列表 [英] AngularJS case-insensitive binding to a static select drop-down

查看:33
本文介绍了AngularJS 不区分大小写绑定到静态选择下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AngularJS 将 ng-model 不区分大小写绑定到静态选择下拉列表.考虑选择元素:

I am trying to perform a case-insensitive bind of an ng-model to a static select drop-down using AngularJS. Consider the select element:

<select id="animal" ng-model="ctrl.animal">
    <option value="">--- Select ---</option>
    <option value="Cat">Cat</option>
    <option value="Dog">Dog</option>
</select>

如果我在我的 Angular 控制器中设置 ctrl.animal="Cat" 绑定工作正常.问题是,如果我设置 ctrl.animal="CAT" 它不会绑定,因为由于大小写差异,字符串不相等.

If I set ctrl.animal="Cat" in my Angular Controller the binding works fine. The issue is that if I set ctrl.animal="CAT" it does not bind because the strings are not equal as a result of the casing difference.

我还尝试将 'value' 属性转换为全部大写,但绑定仍然不起作用.如示例中所示:

I've also tried converting the 'value' attributes to all upper-case but the binding still doesn't work. As-in the sample:

<select id="animal" ng-model="ctrl.animal">
    <option value="">--- Select ---</option>
    <option value="CAT">Cat</option>
    <option value="DOG">Dog</option>
</select>

AngularJS 是否有办法在绑定到选择列表时忽略大小写?或者,至少,使用 'value' 属性中的文本进行绑定,而不是 'option' 元素标记中的内容.

Is there a way for AngularJS to ignore case when binding to a select list? Or, at the very least, use the text in the 'value' attribute for binding instead of what's in the 'option' element tag.

这是一个 JSFiddle

推荐答案

不确定这是否是最佳方式,但您可以创建一个自定义格式化程序来处理模型以查看转换.演示.

Not sure if this is an optimal way, but you can create a custom formatter that will handle model to view convertion. Demo.

angular
  .module('app', [])
  .directive('caseinsensitiveOptions', function() {
    return {
      restrict: 'A',
      require: ['ngModel', 'select'], 
      link: function(scope, el, attrs, ctrls) {
        var ngModel = ctrls[0];

        ngModel.$formatters.push(function(value) {
          var option = [].filter.call(el.children(), function(option) {
            return option.value.toUpperCase() === value.toUpperCase()
          })[0]; //find option using case insensitive search.

          return option ? option.value : value
        });          
      }
    }
  })

  <select id="animal" caseinsensitive-options ng-model="ctrl.animal">

这篇关于AngularJS 不区分大小写绑定到静态选择下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆