How to clear ui-select programmatically?

Question

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?


Show source
| angularjs   | ui-select   2017-01-02 10:01 3 Answers

Answers ( 3 )

  1. 2017-01-02 10:01

    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

  2. 2017-01-02 10:01

    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.

  3. 2017-01-02 11:01

    The problem has been solved. I don't know why but having only selectedCustomerCode in ng-model does not work correctly. I putted the selectedCustomerCode inside an object

    ng-model="selectedCustomer.selectedCustomerCode"
    

    and then I clear it like this

    selectedCustomer.selectedCustomerCode = ''
    

    If I had

    ng-model="selectedCustomerCode"
    

    The clear

    selectedCustomerCode = ''
    

    did not work

◀ Go back