0

In ui-select, when I select an option, the on-select callback does fire, but the option does not clear every second time.

The ui-select has 2 states:

  1. Button - when I do not actually click it
  2. Input - when I click in it and it lets me search

When it starts, the button has my placeholder text "Search...". I click it, start to search, it brings up a list, I select one option, on-select fires, in which I clear the ng-model.

Yet, every second select I do, it ignores the ng-model clear in my callback.

<ui-select ng-model="result.selected" theme="bootstrap" class="search" on-select="searchselect($item)" reset-search-input="true" on-select="selected($item)">
    <ui-select-match placeholder="Search...">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices refresh="search({val:$select.search})" refresh-delay="300" repeat="item in results">
        <div ng-bind="item.name"></div>
    </ui-select-choices>
</ui-select>

Here is my on-select code:

  $scope.selected = function(item) {
     $scope.picked = item;
     $scope.result.selected = "";
  };

I modified the basic ui-select example plunkr to replicate it: http://plnkr.co/edit/16DRYH8MbPJOy0GpogZz?p=preview

  1. Click on the select
  2. Search for text, I find "123" to be easiest
  3. Select an option
  4. See that the ng-model is cleared
  5. Search again
  6. Select another option, or the same one
  7. See that the ng-model is not cleared

Here are images.

Initial:

Initial

During search:

Select

After select (every 2nd one) - this is my problem

After select PROBLEM

Why is it not cleared in the button last image after every 2nd select?

deitch
  • 14,019
  • 14
  • 68
  • 96

1 Answers1

0

late, but maybe it helps: I guess it has something to do with an incorrect implementation of the angular-digest cycle in ui-select. See scope lifecycle of the angular documentation.

So, what can you do about that:

  • Wrap all modifications on scope that you do on the selected-callback in an $timeout, as angular automatically wraps everything in there in a safe digest cycle. Example:

    $scope.selected = function(item) {
      $timeout(function(){
        $scope.picked = item;
        $scope.result.selected = "";
      }); 
    };
    
  • Use a $watch expression instead of the callback function:

    $scope.$watch('result.selected', function(newVal){
      if(newVal !== ''){
        $scope.picked = newVal;
        $scope.result.selected = '';
      }
    }); 
    

I guess the latter is more efficient, as it does not trigger a complete digest cycle. (but I'm not an expert on angular internals.)

ulilicht
  • 737
  • 1
  • 7
  • 18
  • I ended up spending far too much time digging into this, and I think (but am not sure) you are right about the causes. I ended up fixing it by putting my own directive on it. See https://github.com/angular-ui/ui-select/issues/502 – deitch Feb 04 '15 at 09:47