当ui-select标记为需要时,如何重置Angularjs ui-select组件所有选项而没有红色错误突出显示

时间:2017-07-31 11:35:09

标签: javascript html angularjs ui-select

我试图重置所有选择的angularjs ui-select。

  

但ui-select标记为必填字段

。当我将ui-select元素设置为undefined时,如下所示。

$scope.country.selected = undefined;

ui-select元素表示红色的验证错误。无论如何,我想重置选择而不提示现有必需属性的验证错误。

enter image description here

<ui-select required ng-model="country.selected" theme="selectize" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match placeholder="Select or search a country in the list...">
      <span>{{$select.selected.name}}</span>
      <button class="clear" ng-click="clear($event)">X</button>
    </ui-select-match>
    <ui-select-choices repeat="country in countries | filter: $select.search">
      <span ng-bind-html="country.name | highlight: $select.search"></span>
      <small ng-bind-html="country.code | highlight: $select.search"></small>
    </ui-select-choices>
  </ui-select>

1 个答案:

答案 0 :(得分:1)

如下所示添加表单然后您可以setPristine重新初始化表单的状态(您还可以查看plunker链接以查看工作示例):

<form name="formName" novalidate>
    <h3>Selectize theme</h3>
    <p>Selected: {{country.selected}}</p>
    <ui-select required ng-model="country.selected" theme="selectize" ng-disabled="disabled" style="width: 300px;">
      <ui-select-match placeholder="Select or search a country in the list...">
        <span>{{$select.selected.name}}</span>
        <button class="clear" ng-click="clear($event)">X</button>
      </ui-select-match>
      <ui-select-choices repeat="country in countries | filter: $select.search">
        <span ng-bind-html="country.name | highlight: $select.search"></span>
        <small ng-bind-html="country.code | highlight: $select.search"></small>
      </ui-select-choices>
    </ui-select>
</form>

JavaScript

$scope.clear = function($event) {
    $event.stopPropagation(); 
    $scope.country.selected = undefined;
    $scope.formName.$setPristine();
};

您可以看到Working example plunker in here

角度1.3引入了触动的概念:

触及vs pristine :触摸表示字段已模糊,而原始表示字段的值已被修改。 Angular的文档指出,“将表单控制回其未触摸状态通常在将表单设置回其原始状态时很有用。”

$scope.formName.$setUntouched()

我希望这可以提供帮助