AngularJS case insensitive static select dropdown binding

I am trying to do a case-insensitive binding of an ng model to expanding a dropdown 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>

If I install ctrl.animal="Cat"Angular in my controller, the binding works fine. The problem is that if I install ctrl.animal="Cat", it does not bind because the strings are not equal as a result of the difference in the case.

I also tried converting the attributes 'value'to all uppercase, but the binding still does not 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 ? , , "" , 'option'.

JSFiddle

+4
2

, , , . .

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

, , .

(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>
Hide result
+1

All Articles