javascript - Angular $document 全局键盘事件不刷新数据.
ringa_lee
ringa_lee 2017-04-10 14:51:36
[JavaScript讨论组]

非常清晰简单的一个小demo 但是.

angular.module('word', [])
.controller('wordCtrl',['$scope','$document',
function ($scope,$document){


$scope.selectNum = 1;

$document.bind("keypress", function(event) {

    if(event.keyCode == 38){
        $scope.selectNum--;
    }

    if(event.keyCode == 40){
        $scope.selectNum++;
    }
    console.log($scope.selectNum);
});

$scope.$watch('selectNum',function (){
    console.log($scope.selectNum);
})

$scope.getNum = function () {
    $scope.$apply();
    alert($scope.selectNum);
}
}])

$wacth 每次 按 小键盘 上下键都可以成功输出 selectNum的值,但是$watch不会a检测到selectNum值的变动视图{{selectNum}}也无变化. 除非调用一次 getNum()  
ringa_lee
ringa_lee

ringa_lee

全部回复(2)
PHP中文网
$document.bind("keypress", function(event) {
    $scope.$apply(function (){
        if(event.keyCode == 38){
            $scope.selectNum--;
        }
        if(event.keyCode == 40){
            $scope.selectNum++;
        }
    })
});

昨天已经解决了. 这里把代码发出来 方便后面遇到这个问题的朋友吧

PHPz

请查看$scope.$apply $scope.$evalsync $scope.$timeout 几个方法的作用。 另外可以去了解一下 angular的脏值检测和实现的过程。
还有可以 阅读一下这篇文章http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号