Javascript 无法在指令链接中操作继承的作用域(konami代码指令实现)
编辑:本指令的工作程序包括解决方案: 试图创建一个指令,通过监听击键来启用调试模式。它正确地到达了调试模式切换消息,因此我理解我对scope对象的使用是错误的。无法确定我错过了什么,因为showDebug变量在作用域中可用,但未更新:Javascript 无法在指令链接中操作继承的作用域(konami代码指令实现),javascript,angularjs,Javascript,Angularjs,编辑:本指令的工作程序包括解决方案: 试图创建一个指令,通过监听击键来启用调试模式。它正确地到达了调试模式切换消息,因此我理解我对scope对象的使用是错误的。无法确定我错过了什么,因为showDebug变量在作用域中可用,但未更新: app.directive('bpKonamiDebug', ['$document', '$rootScope', function($document, $rootScope) { // Pattern = Konami code
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;
}
});
}
};
}
]);
感谢您的时间Ok,我们发现链接中的逻辑是在指令附加到dom时执行的 请阅读此答案以获得良好的解释: 在我的例子中,事件似乎只需要一个作用域。$apply call