[英]triggerHandler causing Error: [$rootScope:inprog] $apply already in progress error - AngularJS
I am trying to trigger the click of a button when a key is pressed. 我按下按键时尝试触发按钮的单击。 I'm doing this using the
triggerHandler
function, but this is causing the error above. 我正在使用
triggerHandler
函数执行此操作,但这会导致上述错误。 I'm thinking I must have created some kind of circular reference/loop, but I can't see where. 我想我必须创建某种循环引用/循环,但我看不到哪里。
This is my HTML: 这是我的HTML:
<button id="demoBtn1" hot-key-button hot-key="hotKeys.primaryTest" class="po-btn primary-btn" type="submit" ng-click="btnFunction()"></button>
Here's my controller: 这是我的控制器:
.controller('BtnCtrl', function ($scope) {
$scope.checkKeyPress = function ($event, hotKeyObj) {
for(var key in hotKeyObj) {
if($event.keyCode == hotKeyObj[key].keyCode) {
var id = hotKeyObj[key].btnId;
hotKeyObj[key].funcTriggered(id);
}
}
}
$scope.clickFunction = function(id) {
var currentButton = angular.element(document.getElementById(id));
currentButton.triggerHandler("click");
}
$scope.btnFunction = function() {
console.log("clickFunction1 has been triggered");
}
$scope.hotKeys = {
'primaryTest': {
keyCode: 49,
keyShortcut: "1",
label: "Button",
btnId: 'demoBtn1',
funcTriggered: $scope.clickFunction
},
// more objects here
}
}
})
And my directive is here: 我的指示在这里:
.directive("hotKeyButton", function() {
return {
controller: 'BtnCtrl',
scope: {
hotKey: '='
},
transclude: true,
template: "<div class='key-shortcut'>{{hotKey.keyShortcut}}</div><div class='hotkey-label'>{{hotKey.label}}</div>"
};
})
It's a bit of a work in progress, so I suspect there might be small errors in places, but I'm primarily interested in the logic running from the keypress to btnFunction
being triggered. 这是一项正在进行中的工作,所以我怀疑在某些地方可能存在小错误,但我主要感兴趣的是从按键到触发
btnFunction
的逻辑运行。 The error fires on the currentButton.triggerHandler("click")
line. 错误触发
currentButton.triggerHandler("click")
行。
Can anyone see what I've done? 谁能看到我做过的事情? Thanks.
谢谢。
Since you have a problem with $apply
in progress - you can just wrap your triggerHandler
call into $timeout
wrapper - just to make everything you need in another $digest
-cycle, like this: 由于你在使用
$apply
遇到问题 - 你可以将你的triggerHandler
调用包装到$timeout
包装器中 - 只是为了在另一个$digest
triggerHandler
中创建你需要的所有内容,如下所示:
$scope.clickFunction = function(id) {
var currentButton = angular.element(document.getElementById(id));
$timeout(function () {
currentButton.triggerHandler("click");
});
}
After this everything will work OK. 在此之后一切都会好起来的。
$inject
$timeout
service into your BtnCtrl
. BtnCtrl
$inject
$timeout
服务。 controller
property for your directive, but it's not a main case. controller
属性,但它不是主要情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.