Search code examples
angularjskeypressblur

AngularJS submit on blur and blur on keypress


I want to submit some data to the server when a input field is blurred. The User should also be able to blur the input field by pressing enter.

Unfortunately this results in the following: $rootScope:inprog: $apply already in progress error.

Plunkr - thanks in advance!


Solution

  • Here's what's happening:

    • You press enter
    • ng-keydown triggers (digest begins)
    • You call target.blur()
    • ng-blur triggers and attempts to start another digest cycle
    • Angular complains

    The blur is executed synchronously and immediately triggers the handler without finishing the first digest.

    In my opinion, this is not a problem with your code, but rather an Angular bug. I've been trying to think of a better solution, but I can only find:

    app.controller('BlurCtrl', function($scope, $timeout) {
      $scope.blurModel = "I'm the value"
    
        $scope.blurOnEnter = function( $event ) {
          if ( $event.keyCode != 13 )
            return
    
          // this will finish the current digest before triggering the blur
          $timeout(function () { $event.target.blur() }, 0, false);
        }
    
        $scope.onBlur = function() {
        $scope.result = this.blurModel
        }
    })