问题
i'm working with angularJS and i need a way to stop the execution of ng-blur when ng-keydown is executed, since ng-keydown at some point makes the element lose the focus.
The html is:
<div contenteditable ng-show="contentEditableSupport" ng-init="oldName = ''" ng-focus="oldName = userGroup.name" ng-model="userGroup.name" strip-br="true"
ng-blur="editName(userGroup, oldName)" ng-keydown="$event.keyCode === 13 && editName(userGroup, oldName)">{{userGroup.name}}</div>
The angular attribute directive is:
angular.module("mainApp").directive('contenteditable', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, ngModel) {
//Code from: http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/editing-text-in-place-using-html5-content-editable.html
function read() {
ngModel.$setViewValue(element.html());
}
ngModel.$render = function () {
element.html(ngModel.$viewValue || "");
};
element.bind("blur keyup change", function () {
scope.$apply(read);
});
}
};
});
If i edit the text in the element and click elsewhere the editName method is called once, but if i edit it and press enter the method is called twice. I tried to consume $event.stopPropagation and similar with no results.
Thanks in advanced!!
回答1:
Your issue appears to lie in whatever code is triggering the div to lose focus when the user types enter
.
You should be able to fix it by replacing && editName(...)
in your ng-keydown
handler with code that simply causes the control to lose focus. It will then delegate calling editName(...)
to the ng-blur
handler when you press enter
, preventing the duplicate calls.
回答2:
In the directive 'contentEditable' i added:
element.bind("blur keydown", function ($event) {
if ($event.which == 13) {
element[0].blur();
}
});
And i deleted the ng-keydown attribute in the div tag.
Works like a charm
来源:https://stackoverflow.com/questions/49781264/angularjs-prevent-ng-keydown-trigger-ng-blur