Custom directive ng-enter does not pass $ event from html to controller

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

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

Has anyone had this problem before? What is the problem? Why is this happening? links to links are no worse than explanations.

Is there a better way to repeat a 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>
Run codeHide result
+2
source share
2 answers

$eval $scope.$eval(expr, locals), , locals $eval, ($event).

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

+2

. , !:)

: $scope.eval, , . , , , . , , ... 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>
Hide result
+2

Source: https://habr.com/ru/post/1686533/


All Articles