发送点击事件到按钮时,javascript – $应用程序正在进行中?

我的页面上有一个按钮,页面上有一个id =“viewQuestions”:

    <body ng-keydown="key($event);">

我的代码正在检查这样的关键点击:

    $scope.key = function ($event) {
        $scope.$broadcast('key', $event.keyCode)
    }

并在控制器中:

 $scope.$on('key', function (e, key) {
        if (key == 13) {
            if (ts.test.current && ts.test.userTestId) {
                document.getElementById("viewQuestions").click();
            }               
        }
    });

当我运行代码并点击ENTER,我得到这个错误:

 Error: [$rootScope:inprog] $apply already in progress
http://errors.angularjs.org/1.3.7/$rootScope/inprog?p0=%24apply
    at REGEX_STRING_REGEXP (http://localhost:2757/lib/angular/angular.js:63:12)
    at beginPhase (http://localhost:2757/lib/angular/angular.js:14735:15)
    at Scope.$get.Scope.$apply (http://localhost:2757/lib/angular/angular.js:14479:11)
    at HTMLButtonElement.<anonymous> (http://localhost:2757/lib/angular/angular.js:22945:23)
    at HTMLButtonElement.eventHandler (http://localhost:2757/lib/angular/angular.js:3009:21)
    at http://localhost:2757/app/tests/controllers/TestsController.js:24:62
    at Scope.$get.Scope.$broadcast (http://localhost:2757/lib/angular/angular.js:14700:28)
    at Scope.AppController.$scope.key (http://localhost:2757/app/appController.js:30:20)
    at $parseFunctionCall (http://localhost:2757/lib/angular/angular.js:12330:18)
    at ngEventDirectives.(anonymous function).compile.element.on.callback (http://localhost:2757/lib/angular/angular.js:22940:17)

任何人都可以给我这方面的建议。当按下ENTER键时,我只想模拟一个按钮的点击。我确实尝试了形式的解决方案,但不符合我相当复杂的需求。

最佳答案
您的点击事件正在运行与当前摘要循环相冲突的摘要循环,$ timeout将帮助您在这种情况下。在$ timeout函数内包装click事件。

标记

<body ng-app="myApp" ng-controller="testCtrl" ng-keydown="key($event);">
    <button id="viewQuestions" type="button" ng-click="isButtonClicked = !isButtonClicked; test();"> Test</button>
    Is Button Clicked {{isButtonClicked}}
</body>

$scope.$on('key', function (e, key) {
    if (key == 13) {
        if (ts.test.current && ts.test.userTestId) {
            $timeout(function(){
                angular.element(document.getElementById("viewQuestions")).trigger('click');
            })
        }               
    }
});

无论您在ng-click中写的内容将被调用。

Working Fiddle

转载注明原文:发送点击事件到按钮时,javascript – $应用程序正在进行中? - 代码日志