AngularJS-防止ng-keydown触发ng-blur [英] AngularJS - prevent ng-keydown trigger ng-blur

查看:24
本文介绍了AngularJS-防止ng-keydown触发ng-blur的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angularJS,我需要一种在执行ng-keydown时停止执行ng-blur的方法,因为ng-keydown有时会使元素失去焦点.

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.

html是:

<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>

angular属性指令为:

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);
          });

      }
  };

});

如果我编辑元素中的文本并单击其他位置,则一次调用editName方法,但是如果我对其进行编辑并按Enter,则调用该方法两次.我尝试使用$ event.stopPropagation及类似内容,但没有结果.

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.

感谢进阶!

推荐答案

在指令"contentEditable"中,我添加了:

In the directive 'contentEditable' i added:

          element.bind("blur keydown", function ($event) {
              if ($event.which == 13) {
                  element[0].blur();
              }
          });

然后我删除了div标签中的ng-keydown属性.

And i deleted the ng-keydown attribute in the div tag.

像魅力一样工作

这篇关于AngularJS-防止ng-keydown触发ng-blur的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆