triggerHandler导致错误:[$ rootScope:inprog] $ apply已在执行中错误-AngularJS [英] triggerHandler causing Error: [$rootScope:inprog] $apply already in progress error - AngularJS
问题描述
我正在尝试在按下某个键时触发按钮的单击.我正在使用triggerHandler
函数执行此操作,但这会导致上述错误.我想我一定已经创建了某种循环引用/循环,但是我看不到哪里.
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. I'm thinking I must have created some kind of circular reference/loop, but I can't see where.
这是我的HTML:
<button id="demoBtn1" hot-key-button hot-key="hotKeys.primaryTest" class="po-btn primary-btn" type="submit" ng-click="btnFunction()"></button>
这是我的控制器:
.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
}
}
})
我的指令在这里:
.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>"
};
})
这项工作尚在进行中,所以我怀疑某些地方可能存在小错误,但是我主要是对从按键到触发btnFunction
的逻辑感兴趣.错误在currentButton.triggerHandler("click")
行上触发.
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. The error fires on the currentButton.triggerHandler("click")
line.
任何人都可以看到我的工作吗?谢谢.
Can anyone see what I've done? Thanks.
推荐答案
由于您在进行$apply
时遇到问题-您只需将triggerHandler
调用包装到$timeout
包装器中-即可满足所需在另一个$digest
循环中,如下所示:
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:
$scope.clickFunction = function(id) {
var currentButton = angular.element(document.getElementById(id));
$timeout(function () {
currentButton.triggerHandler("click");
});
}
此后一切正常.
- 也不要忘记将
$inject
$timeout
服务纳入您的BtnCtrl
. - 此外,我不确定您是否需要为指令定义
controller
属性,但这不是主要情况.
- Also don't forget to
$inject
$timeout
service into yourBtnCtrl
. - Also i'm not sure you need to define
controller
property for your directive, but it's not a main case.
这篇关于triggerHandler导致错误:[$ rootScope:inprog] $ apply已在执行中错误-AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!