angularJS valdr + ui-select验证

时间:2015-03-16 15:15:09

标签: angularjs angularjs-directive ui-select angularjs-ui-utils valdr

我在这个问题上用Google搜索,但仍无法找到正确的讨论。我们在一个表单(angularJS app)中使用valdr和ui select,我们遇到的问题是ui-select渲染的输入不会获得name属性,因此,angular会抛出一个错误:

Error: Form element with ID "undefined" is not bound to a field name.
at d.link (http://localhost:8080/bower_components/valdr/valdr.min.js:1:8414)
at invokeLinkFn (http://localhost:8080/bower_components/angular/angular.js:8141:9)
at nodeLinkFn (http://localhost:8080/bower_components/angular/angular.js:7653:11)
at compositeLinkFn (http://localhost:8080/bower_components/angular/angular.js:7009:13)
at nodeLinkFn (http://localhost:8080/bower_components/angular/angular.js:7648:24)
at http://localhost:8080/bower_components/angular/angular.js:7884:13
at processQueue (http://localhost:8080/bower_components/angular/angular.js:13071:27)
at http://localhost:8080/bower_components/angular/angular.js:13087:27
at Scope.$get.Scope.$eval (http://localhost:8080/bower_components/angular/angular.js:14287:28)
at Scope.$get.Scope.$digest (http://localhost:8080/bower_components/angular/angular.js:14103:31) <input type="text" autocomplete="off" tabindex="-1" aria-expanded="true" aria-label="{{ $select.baseTitle }}" aria-owns="ui-select-choices-{{ $select.generatedId }}" aria-activedescendant="ui-select-choices-row-{{ $select.generatedId }}-{{ $select.activeIndex }}" class="form-control ui-select-search ng-pristine ng-untouched ng-valid" placeholder="{{$select.placeholder}}" ng-model="$select.search" ng-show="$select.searchEnabled &amp;&amp; $select.open">

所以我们在ui-select指令上尝试了一些hack-select指令,例如templateCache重写/修改,隐藏的输入具有相同的模型,但结果是相同的。

Btw templateCache重写是最糟糕的方法,因为其他指令在appwide中使用了这个指令,我们不能破解整个应用程序。

有没有人遇到过这个问题?

代码段 http://plnkr.co/edit/sDNDDtnhi7Jxi9mtjDTl?p=preview

1 个答案:

答案 0 :(得分:8)

如果输入元素name上没有valdr属性则抛出异常。

ui-select在内部创建一个没有name属性的输入字段。因此错误。

您可以尝试这样来摆脱错误。

directive('input', function () {
    var count = 0;
    return {
      restrict: 'E',
      compile: function () {
        return {
          pre: function (scope, element, attrs) {
            // if the input is created by ui-select and has ng-model
            if (element.hasClass('ui-select-search') && attrs.ngModel) {
              if (!attrs.name) { // if the input is not having any name
                attrs.name = 'ui-select' + (++count); // assign name
              }
            }
          }
        }
      }
    }
  })

Working Plnkr