1

我正在使用ui-select一些多选字段,我想实现这样的客户端<form>验证:

<form name="newProjectForm" ng-submit="p.addProject()" class="inputsContainer" novalidate> 
  <div class="form-group" ng-class="{ 'has-error' : newProjectForm.frameworks.$invalid && 
                                                    !newProjectForm.frameworks.$pristine }">
    <label>Frameworks</label>
  <ui-select name="frameworks" multiple ng-model="p.newProject.frameworks" sortable="true" 
             close-on-select="false" required>
    <ui-select-match placeholder="Select framework...">{{$item.name}}</ui-select-match>
    <ui-select-choices repeat="framework.id as framework in p.frameworksList
                               | propsFilter: {name: $select.search, language: $select.search}">
      <div ng-bind-html="framework.name | highlight: $select.search"></div>
      <small>
        language : <span ng-bind-html="''+framework.language | highlight: $select.search"></span>
      </small>
    </ui-select-choices>
  </ui-select>
    <div ng-messages="newProjectForm.frameworks.$error">
      <p ng-messages="required">THIS IS REQUIRED</p>
    </div>
    <p ng-show="newProjectForm.frameworks.$invalid && !newProjectForm.frameworks.$pristine" 
       class="help-block">Project frameworks is required.</p>
  </div>
<!-- ... -->

所以,问题是我尝试的条件不起作用:

newProjectForm.frameworks.$invalid && !newProjectForm.frameworks.$pristine">似乎总是假的。

<div ng-messages="newProjectForm.frameworks.$error">似乎也不起作用。

但是,我改用这条线进行了测试:

<div class="form-group" ng-class="{ 'has-error' : true }">

它奏效了,所以我猜这是不起作用的条件。

4

1 回答 1

0

好的,所以看起来ui-selectrequired不能一起工作。

因此,如果您遇到同样的问题,您可以使用自定义指令而不是 required :

app.directive('uiSelectRequired', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$validators.uiSelectRequired = function(modelValue, viewValue) {
        if (modelValue && modelValue.length > 0)
          return true;
        return false;
      };
    }
  };
});

然后你只需要在 HTML 视图中替换required为。ui-select-required

于 2015-11-06T09:40:12.597 回答