加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 10:17:34 所属栏目:安全 来源:网络整理
导读:我已经提出了这个代码: 在我的外部控制器中: $scope.key = function ($event) { $scope.$broadcast('key',$event.keyCode) } 在我的内部控制器(我有不止这样的) $scope.$on('key',function (e,key) { if (key == 13) { if (ts.test.current) { var btn = n
我已经提出了这个代码:

在我的外部控制器中:

$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);
                })
            } 
        }
    });

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

请检查这个要点,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);
})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读