简体   繁体   中英

How to reset the Angularjs ui-select component all selections without red color error highlight when ui-select marked as required

I'm trying to reset all selection of angularjs ui-select.

but ui-select marked as required field

.so that when I set the ui-select element as undefined as shown below.

$scope.country.selected = undefined;

ui-select element indicates a validation error with red colour.Anyway, i want to reset selection without prompting validation error with the existing required attribute.

在此处输入图片说明

<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>

Add a form as bellow then you can setPristine to reinitialize the status of the form (You can also see the plunker link to see the working example):

<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();
};

You can see the Working example plunker in here

The angular 1.3 introduced the touched concept:

touched vs pristine : touched means the field has been blurred while pristine means the field's value has been modified. Angular's docs note that "Setting a form controls back to their untouched state is often useful when setting the form back to its pristine state."

$scope.formName.$setUntouched()

I hope this can help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM