我可以使用AngularJS简化点击回车键吗?

Sam*_*tar 6 angularjs

我已经提出了这个代码:

在我的外部控制器中:

    $scope.key = function ($event) {
        $scope.$broadcast('key', $event.keyCode)
    }
Run Code Online (Sandbox Code Playgroud)

在我的内部控制器(我有不止这样的)

    $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);
                })
            } 
        }
    });
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以使用我未包含的AngularJS的某些功能来简化这一点?

all*_*kim 6

请查看这个要点,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();
      }
    });
  };
});
Run Code Online (Sandbox Code Playgroud)

HTML

<input ng-enter="myControllerFunction()" />
Run Code Online (Sandbox Code Playgroud)

您可以将名称更改为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);
})
Run Code Online (Sandbox Code Playgroud)