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

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

问题描述

我正在尝试使用AngularJS对ng模型与静态选择下拉列表执行不区分大小写的绑定.考虑选择元素:

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 Controller中设置了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' element标签中的文本.

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天全站免登陆