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

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

问题描述

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

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.

是否有比复制两次方法调用更好的方法? (第二)

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

预览

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

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