自定义 ng-enter 指令不将 $event 从 html 传递给控制器

Custom ng-enter directive not passing $event from html to the controller

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

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

以前有人遇到过这个问题吗?问题是什么?为什么会这样?参考文献的链接与解释一样好。

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

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 方法看起来像这样 $scope.$eval(expr, locals),这意味着您可以使用 $eval 函数的 locals 对象,其中键将是参数名称( $event).

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

Preview

我稍微更改了您的代码片段。看看并告诉我们这是否适合您! :)

说明:$scope.eval,正如函数名所说,计算你传递的表达式。如果表达式是一个函数的原型,该方法将 return 您评估的函数,以便您可以执行它。所以,你有要执行的函数和你想要的参数,所以... 1 + 1 = 2 jajajajaja.

希望对您有所帮助。如果您有任何问题,请直接提问 :)

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() {
          var directiveFunction = scope.$eval(attrs.mvEnter);
          if (angular.isFunction(directiveFunction)) {
            directiveFunction(event);
          }
        });
        event.preventDefault();
      }
    });
  };
});
<!DOCTYPE html>
<html>
<head></head>

<body ng-app='app'>
  <div ng-controller="submitCtrl">
    <textarea mv-enter="submitContent"></textarea>
  </div>

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

</html>