自定义 ng-enter 指令不将 $event 从 html 传递到控制器 [英] Custom ng-enter directive not passing $event from html to the controller

查看:9
本文介绍了自定义 ng-enter 指令不将 $event 从 html 传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个自定义指令来检测用户何时按下回车键,然后调用在周围表单元素的 ngSubmit 中调用的相同函数.

下面是我的问题的演示,我需要从控制器内部访问事件,但它始终未定义.

有人遇到过这个问题吗?问题是什么?为什么会发生?参考文献的链接和解释一样好.

有没有比重复两次方法调用更好的方法?(次要)

var app = angular.module('app', []);app.controller('submitCtrl', ['$scope', function($scope) {$scope.submitContent = 函数(事件){//这就是我要找的.控制台日志(事件);//这是未定义的.}}]);app.directive('mvEnter', function() {返回函数(范围,元素,属性){element.bind('keydown keypress', function(event) {if (event.which === 13) {范围.$应用(函数(){范围.$eval(attrs.mvEnter);});event.preventDefault();}});};});

<头></头><body ng-app='app'><div ng-controller="submitCtrl"><textarea mv-enter="submitContent($event);"></textarea>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script></html>

解决方案

$eval 方法看起来像这样 $scope.$eval(expr, locals),这意味着你可以使用$eval 函数的 locals 对象,其中的键是参数名称($event).

scope.$eval(attrs.mvEnter, {$event: event});

预览

I am using a custom directive that detects when the user presses enter and then calls the same function that is called in the ngSubmit of the surrounding form element.

Below is a demonstration of my problem, I need access to the event from within the controller but it is always undefined.

Has anyone had this issue before? What is the issue? Why is it happening? links to refs are just as good as explanations.

Is there a better way then duplicating the method call twice? (secondary)

var app = angular.module('app', []);

app.controller('submitCtrl', ['$scope', function($scope) {

  $scope.submitContent = function(event) {
    //This is what I am looking for.
    console.log(event); //This is undefined. 
  }
}]);

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

<!DOCTYPE html>
<html>
<head></head>

<body ng-app='app'>
  <div ng-controller="submitCtrl">
    <textarea mv-enter="submitContent($event);"></textarea>
  </div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>

</html>

解决方案

$eval method looks like this $scope.$eval(expr, locals), that means you can use the locals object of the $eval function, where the key will be the parameter name($event).

scope.$eval(attrs.mvEnter, {$event: event});

Preview

这篇关于自定义 ng-enter 指令不将 $event 从 html 传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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