user3318489 user3318489 - 8 days ago 6
AngularJS Question

AngularJS ngEnter - function is invoked twice

I have this input with the directive ngEnter and if I press enter than the function convertAdditionalHoursInHoliday is invoked twice - only the first time. If I press enter once again than the function is only invoked once.
Does anyone have any idee why or hao I can prevent this?

<input type="text" name="additionalHoursInHolidayAmount"
ng-model="institutionUserConnection.scheduleAbsenceHeader.additionalHoursInHoliday"
ng-Enter="vm.convertAdditionalHoursInHoliday(institutionUserConnection)"
ng-class="institutionUserConnection.scheduleAbsenceHeader.errorTimeAdditionalHoursInHoliday ? 'form-control input errorTime' : 'form-control input'"
placeholder="00:00" />


The directive looks like this:

(function() {
'use strict';

angular
.module('aposoft.userschedulemanagement')
.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.ngEnter);
});

event.preventDefault();
}
});
};
});


})();

Answer

I had this problem as well.. couldn't understand why in certain functions ng-enter works as expected and in other functions it is invoked twice.

Had to find a quick fix for this issue, so I found this option:

<input ng-keyup="$event.keyCode == 13 && tempFunc()"... />

in your case it would look like that:

<input type="text" name="additionalHoursInHolidayAmount"   
    ng-model="institutionUserConnection.scheduleAbsenceHeader.additionalHoursInHoliday" 
    ng-keyup="$event.keyCode == 13 && vm.convertAdditionalHoursInHoliday(institutionUserConnection)"
    ng-class="institutionUserConnection.scheduleAbsenceHeader.errorTimeAdditionalHoursInHoliday ? 'form-control input errorTime' : 'form-control input'" 
    placeholder="00:00" />

In my case it worked like a charm.. You should check it out.

If there is any insight about why the ng-enter directive is invoked twice, I would love to be informed as well..

Hopefully this solution helps for now :)

=====================================================

I think I found a better solution working with the directive.

Adding both the keydown and keypress events without a comma to delimit them means both may fire simultaneously. This is likely to spawn $rootScope:inprog errors. Adding a comma between them creates a disjunctive, and ensures only only $digest cycle occurs. (found this comment by Ryan Miller in another post - thanks Ryan)

so what we get for the working directive is (drum roll):

.directive('ngEnter', function () {
  return function (scope, element, attrs) {
    element.bind("keydown, keypress", function (event) {
      if(event.which === 13) {
        scope.$apply(function (){
          scope.$eval(attrs.ngEnter);
        });
        event.preventDefault();
      }
    });
  };
});

I have checked it on my code and it works like a charm.

Cheers.

Comments