AngularJS不区分大小写绑定到动态选择下拉列表而不将ng-bind值更改为大写或小写

时间:2017-01-07 06:17:41

标签: javascript angularjs json filter formatter

我正在尝试使用AngularJS对动态选择下拉列表执行不区分大小写的ng-model绑定。

通过浏览堆栈中的各种其他相关答案,我在视图中提出了类似下面的内容,这里caseinsensitive-options是一个指令,我已经提出引用以下解决方案

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

HTML:

<select id="dcName" caseinsensitive-options="" ng-model="DC.name" class="form-control">
  <option value="">--- Please Select ---</option>
  <option ng-repeat="dataCenter in inventoryDataCenters" value="{{dataCenter}}">{{dataCenter}}</option>
</select>

js指令代码:

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];
            return option ? option.value : value
          });

        }
      }
    });

预期结果是

当我传递这样的东西时 $ scope.inventoryDataCenters = [&#34; TEST1&#34;,&#34; test2&#34;,teST3];并且DC.name的ng-model具有值TesT1。

下拉列表应通过不区分大小写的绑定来显示TEST1。那现在不会发生。当我们有静态下拉时,上述解决方案非常有效。

需要考虑的事情是选择是在div内部进行ng-repeat,如下所示

ng-repeat="DC in workflowData.project_data.service_info.variables.service_data['data-center']" 
选择DC.name的

和ng-model来自上面的数组DC。

1 个答案:

答案 0 :(得分:0)

根据不区分大小写的值检查此URL以进行绑定

https://jsfiddle.net/dwd2du17/6/

 <div ng-app="module" ng-controller="controller as ctrl">
 <select id="animal" ng-model="ctrl.animal">
  <option value="">--- Select ---</option>
  <option value="CaT">Cat</option>
  <option value="DOg">Dog</option>
 </select>
 {{ctrl.animal}}
 </div>


 var appForm = angular.module('module', [])
 .controller('controller', function($scope) {
 });