我有这样的指示,转到模态窗口中的下一个输入(或按钮):
.directive('autoVrm', function () {
return function (scope, element, attrs) {
var counter = 0;
element.bind("keydown keypress", function (event) {
console.log(element);
if(event.which === 13) {
counter++;
event.preventDefault();
var elementToFocus = element.find('input')[counter] || element.find('button')[1];
console.log(elementToFocus.type);
if(angular.isDefined(elementToFocus))
elementToFocus.focus();
if (elementToFocus.type === 'button'){
counter = -1;
elementToFocus.bind("keydown keypress", function (eventSubmit) {
if(eventSubmit.which === 13) {
console.log('submit');
}
});
}
}
});
};
但我有一个麻烦,如果我在按钮上,然后点击输入我得到:
Uncaught TypeError: undefined is not a function
但为什么呢?如何进入点击提交表格?不依赖于控制器?
答案 0 :(得分:2)
尝试使用angular.element(elementToFocus).bind作为Uncaught TypeError。
关于你的新评论:
如果在控制器中定义了
$scope.registerUser = function() {
...
}
然后只需通过
在指令中调用它elementToFocus.bind("keydown keypress", function (eventSubmit) {
if(eventSubmit.which === 13) {
scope.registerUser();
}
});
作为一种猜测,您可以执行以下操作:检查 attrs 参数以获取'data-ng-click'的值并调用相应的函数:
elementToFocus.bind("keydown keypress", function (eventSubmit) {
if(eventSubmit.which === 13) {
if (attrs.dataNgClick == "registerUser()" {
scope.registerUser();
}
else if (attrs.dataNgClick == "sign()" {
scope.sign();
}
else if (attrs.dataNgClick == "frgtPassword()" {
scope.frgtPassword();
}
}
});
答案 1 :(得分:1)
此行为已在Web技术中定义。当您在表单中按Enter时,它将被提交。为此,您需要处理正确的事件(ng-submit)。您可以使用更少的代码来实现您正在寻找的效果。
angular.module('app', [])
.controller('MyCtrl', function () {
var self = this;
self.message = "press ENTER to submit";
self.count = 0;
this.onSubmit = function () {
self.count++;
self.message = "form submitted " + self.count + " times";
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@*" data-semver="1.4.0-beta.1" src="https://code.angularjs.org/1.4.0-beta.1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MyCtrl as ctrl">
<h1>Hello Stack Overflow!</h1>
<form ng-submit="ctrl.onSubmit()">
<input type="text" placeholder="press ENTER"/>
<input type="text" placeholder="press ENTER"/>
<input type="submit" value="Send" />
</form>
<div>{{ctrl.message}}</div>
</body>
</html>