vagelis
vagelis

Reputation: 464

How to clear ui-select programmatically?

I would like to find a way to clear the selection of a ui-select by code.

For example I have the following code

<ui-select ng-model="selectedCustomerCode" ng-if="CustomerIds.length>1" on-select="CustomerCodeFiltersOnSelectCallback($item, $model)" theme="bootstrap">
  <ui-select-match class="ui-select-match" allow-clear="true" placeholder="Επιλογή κωδικού πελάτη...">{{$select.selected.CCode}}</ui-select-match>
  <ui-select-choices class="ui-select-choices" repeat="customer in CustomerIds | propsFilter: {CCode: $select.search}">
    <div ng-bind-html="customer.CCode | highlight: $select.search"></div>
  </ui-select-choices>
</ui-select>

I want to clink on a clear button and clear some inputs including the ui-select. What is the code in order to clear ui-select?

Upvotes: 3

Views: 8400

Answers (5)

ksenija
ksenija

Reputation: 33

What you can do in cases when in general you want ui-select cleared is to declare ng-model on your ui-select for example as:

ng-model="selectedCustomerCode.code"

and in your controlller you wold initialize object as:

$scope.selectedCustomerCode = {};

and whenever later in code you need this property cleared you would simply reinitialize it as follows:

$scope.selectedCustomerCode = {};

Upvotes: 0

LiefLayer
LiefLayer

Reputation: 1073

Another possible solution that I used today is to create an empty state by adding a clear element to the list repeated in the ui-select-choices

vm.CustomerIds.unshift({"CCode":"Select..."});

Upvotes: 0

vagelis
vagelis

Reputation: 464

The problem has been solved. I don't know why, but having only selectedCustomerCode in ng-model did not work properly. I assigned the selectedCustomerCode as an object:

ng-model="selectedCustomer.selectedCustomerCode"

then I was able to clear it like this:

selectedCustomer.selectedCustomerCode = ''

If I had

ng-model="selectedCustomerCode"

then reassigning it to:

selectedCustomerCode = ''

somehow does not work.

Upvotes: 7

You should clear cont.selectedCustomerCode variable:

<button ng-click="cont.selectedCustomerCode = ''">clear</button>

Edit:

You should consider exposing you attributes on a variable. That's the recommended way.

Upvotes: 2

Jitendra gupta
Jitendra gupta

Reputation: 108

There is an option allow-clear for ui-select-match that does the thing for you, you will have the x on the right and you can clear it by clicking it. https://github.com/angular-ui/ui-select/wiki/ui-select-match

<ui-select-match allow-clear="true" placeholder="Select or search in a list...">
  <span>{{$select.selected.name}}</span>
</ui-select-match>

working example http://plnkr.co/edit/DbbUE68QlNLjx97pBZ56?p=preview

Upvotes: 1

Related Questions