Note: Check out the working plunker for this directive with a solution: http://embed.plnkr.co/UhFCVa/
I am attempting to develop a directive that will activate a debug mode by detecting keystrokes. I can see the "debug mode toggle" message, indicating that there may be an issue with how I am utilizing the scope object. Despite having the "showDebug" variable accessible in the scope, it does not seem to update as expected:
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
// This is where the variable is set (works)
scope.showDebug = true;
// Bind document's keydown event
$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');
// This is where I fail to change the value
scope.showDebug = !scope.showDebug;
cursor = 0;
}
}
else{
cursor = 0;
}
});
}
};
}
]);
Thank you for your assistance.