编辑:此指令的工作plunker(包括解决方案): http://embed.plnkr.co/UhFCVa/
尝试通过监听击键来创建指令以启用调试模式。它正确地达到"调试模式切换"消息,所以我理解我对scope对象的使用是错误的。无法想象自从#de; showDebug"" showDebug"变量在范围内可用,但未更新:
app.directive('bpKonamiDebug', ['$document', '$rootScope',
function($document, $rootScope) {
// Pattern = Konami code (↑ ↑ ↓ ↓ ← → ← → B A)
var pattern = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
// Pattern = "debug"
// var pattern = [100, 101, 98, 117, 103]; // keycodes for "debug"
var cursor = 0;
return {
restrict: 'A',
link: function(scope, element, attrs) {
// Enrich parent scope
// stackoverflow: This is where the variable is set (works)
scope.showDebug = true;
// Bind document's keydown event (rem: keypress is trapped by navigation handler, pans the screen and disables propagation)
$document.bind('keydown', function(event) {
// Obtain keycode
var keycode = event.which;
// Compare keycode with expected character
if(pattern[cursor] == keycode){
// End of the pattern?
if(pattern.length == ++cursor){
console.log('debug mode toggle');
// stackoverflow: This is where I fail to change the value
scope.showDebug = !scope.showDebug;
cursor = 0;
}
}
else{
cursor = 0;
}
});
}
};
}
]);
感谢您的时间
答案 0 :(得分:0)
好的,发现"链接"中的逻辑当指令附加到dom时执行。
阅读此答案以获得一个很好的解释: AngularJS: What is the need of the directive's link function when we already had directive's controller with scope?
就我而言,事件似乎需要一个范围。$ apply()调用。