问题
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>
回答1:
$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
回答2:
I changed a little your code snippet. Take a look and tell us if this worked for you! :)
Explanation: $scope.eval, as the name of the function says, evaluates the expression you passed. If the expression is a prototype of a function, the method will return the function you evaluated so you can execute it. So, you have the function to execute and the parameter you want, so... 1 + 1 = 2 jajajajaja.
I hope this helped you. If you have any question, just ask :)
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>
来源:https://stackoverflow.com/questions/46177252/custom-ng-enter-directive-not-passing-event-from-html-to-the-controller