我已经提出了这个代码:
在我的外部控制器中:
$scope.key = function ($event) { $scope.$broadcast('key',$event.keyCode) }
在我的内部控制器(我有不止这样的)
$scope.$on('key',function (e,key) { if (key == 13) { if (ts.test.current) { var btn = null; if (ts.test.userTestId) { btn = document.getElementById('viewQuestions'); } else { btn = document.getElementById('acquireTest'); } $timeout(function () { btn.focus(); btn.click(); window.setTimeout(function () { btn.blur(); },500); }) } } });
请检查这个要点,https://gist.github.com/EpokK/5884263
您只需创建一个指令ng-enter并将您的操作作为参数传递
app.directive('ngEnter',function() { return function(scope,element,attrs) { element.bind("keydown keypress",function(event) { if(event.which === 13) { scope.$apply(function(){ scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; });
HTML
<input ng-enter="myControllerFunction()" />
您可以将名称ng-enter更改为不同的名称,因为ng – **是Angular核心团队保留的.
另外我看到你的控制器正在处理DOM,你不应该.将这些逻辑移动到其他指令或HTML,并保持您的控制器精益.
if (ts.test.userTestId) { btn = document.getElementById('viewQuestions'); //NOT in controller } else { btn = document.getElementById('acquireTest'); //NOT in controller } $timeout(function () { btn.focus(); //NOT in controller btn.click(); //NOT in controller window.setTimeout(function () { // $timeout in $timeout,questionable btn.blur(); //NOT in controller },500); })