AngularJS - prevent ng-keydown trigger ng-blur

本小妞迷上赌 提交于 2021-02-11 08:51:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!