角度ngmodel - AngularJS不区分大小写绑定到静态选择下拉列表



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

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

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

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

<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'元素标记中的文本。

这是一个JSFiddle

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

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">

您可以将选项值转换为大写或小写,以便您知道它将始终处于特定大小写中。

(function() {
  'use strict';
  angular
    .module('exampleApp', [])
    .controller('ExampleController', ExampleController);
  function ExampleController() {
    var vm = this;
    vm.dropDownValues = [{
      value: "Cat",
      name: "Cat"
    }, {
      value: "Dog",
      name: "Dog"
    }];
    vm.animal = "CAT";
    /*
    // probably easier to just select the first element
    vm.animal = vm.dropDownValues[0].value;
    */
  }
})();
<!DOCTYPE html>
<html ng-app='exampleApp'>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
</head>
<body ng-controller="ExampleController as vm">
  <select ng-model="vm.animal" ng-options="(animal.value | uppercase) as animal.name for animal in vm.dropDownValues">
  </select>
</body>
</html>

最新更新