Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法在指令链接中操作继承的作用域(konami代码指令实现)_Javascript_Angularjs - Fatal编程技术网

Javascript 无法在指令链接中操作继承的作用域(konami代码指令实现)

Javascript 无法在指令链接中操作继承的作用域(konami代码指令实现),javascript,angularjs,Javascript,Angularjs,编辑:本指令的工作程序包括解决方案: 试图创建一个指令,通过监听击键来启用调试模式。它正确地到达了调试模式切换消息,因此我理解我对scope对象的使用是错误的。无法确定我错过了什么,因为showDebug变量在作用域中可用,但未更新: app.directive('bpKonamiDebug', ['$document', '$rootScope', function($document, $rootScope) { // Pattern = Konami code

编辑:本指令的工作程序包括解决方案:

试图创建一个指令,通过监听击键来启用调试模式。它正确地到达了调试模式切换消息,因此我理解我对scope对象的使用是错误的。无法确定我错过了什么,因为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;
                    }
                });
            }
        };
    }
]);

感谢您的时间

Ok,我们发现链接中的逻辑是在指令附加到dom时执行的

请阅读此答案以获得良好的解释:

在我的例子中,事件似乎只需要一个作用域。$apply call