问题
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
回答1:
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">
回答2:
You can convert the option value to uppercase or lowercase so that you know it will always be in a specific case.
(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>
来源:https://stackoverflow.com/questions/38343966/angularjs-case-insensitive-binding-to-a-static-select-drop-down