Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$apply already in progress error when using typeahead plugin (found to be related to ng-focus + ng-blur)

My main problem is that the error is not pointing anywhere in my code and we dont have that many $apply calls in our project. The code that seems to be generating the error:

 <input type="text" 
  placeholder="{{ $root.pg.t('HEADER.CITY_OR_POSTAL') }}"
  data-ng-focus="decideToStop();" data-ng-blur="decideToStart()"
  data-ng-model="search.selected" 
  typeahead-on-select="search.locationQuery(geo_locations, search.selected)" 
  typeahead="location.name for location in getLocations($viewValue) | filter: $viewValue | limitTo:8" class="semi-bold">

In the controller:

$scope.decideToStop = function(){
  if($scope.actionTimeout){
    $timeout.cancel($scope.actionTimeout);
    $scope.actionTimeout = {};
  }


  $scope.MyService.CustomMethodThatDoesALotOfThings();
};


$scope.decideToStart = function(){
  if(CustomCondition()){
    $scope.actionTimeout = $timeout(function(){
      $scope.MyService.AnotherCustomMethodThatDoesALotOfThings();

    }, 150);

  }
};

$root.pg is just the polyglot.js library inside a service that is placed in the rootScope for now. search is the service corresponding to the location search.

I am getting the error when I change the city in the input field. I have no idea how to debug this...

like image 904
Alex C Avatar asked Mar 27 '14 20:03

Alex C


1 Answers

This is a problem with using ng-focus and other event directives at the same time. Most often, it happens when you use one of the event directives (ng-click, ng-blur) to focus an element that has ng-focus. It's actually a bug, but you can fix it easily. Best option is to write your own directive that applies the function async:

app.directive('ngFocusAsync', ['$parse', function($parse) {
  return {
    compile: function($element, attr) {
      var fn = $parse(attr.ngFocusAsync);
      return function(scope, element) {
        element.on('focus', function(event) {
          scope.$evalAsync(function() {
            fn(scope, {$event:event});
          });
        });
      };
    }
  };
}]

)

If you don't want to do this, you can take the contents of the directive and apply it to your element manually, but since the directive is so small, the directive is preferable. When this gets fixed in core, you can then simply replace all your declarations.

See an example here: http://plnkr.co/edit/GBdvtN6ayo59017rLKPs?p=preview If your replace ng-focus-async with ng-focus, angular will throw when you click the button, or when you blur the second input field.

like image 113
Narretz Avatar answered Nov 08 '22 20:11

Narretz