Search code examples
angularjsangular-ngmodel

AngularJS case-insensitive binding to a static select drop-down


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>

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.

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>

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.

Here's a JSFiddle


Solution

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