范围更新后如何更新 angularjs 页面? [英] How do I update an angularjs page after a scope update?

查看:30
本文介绍了范围更新后如何更新 angularjs 页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个捕获键盘事件的指令,并在某些键上更新了作用域中的一些对象.这个想法是上下移动数组并显示所选行的详细信息.问题是页面不会更新,直到我执行另一个更新页面的操作.我该如何强制执行此操作?

I have written a directive that captures keyboard events, and on certain keys I update some objects in the scope. The idea is to move up and down an array and display the selected row details. The problem is the page is not updated until I do another action that updates the page. How can I force this?

指令如下:

LogApp.directive("keyCapture", [function(){
    var scopeInit;
    return{
        link: function(scope, element, attrs, controller){
            scopeInit = scope
            element.on('keydown', function(e){
                scopeInit[attrs.keyCapture].apply(null, [e]);                
            });
        }
    }
}]);

这样绑定模板:

<body ng-controller="logCtrl" key-capture="movePreview">

控制器方法:

$scope.movePreview = function(e){
    if ($scope.events.length === 0)
        return;
    // Find the element 
    if (e.keyCode === 38 || e.keyCode === 40){
        console.log("Pressed %s", e.keyCode);
        var offset = 0;
        if (e.keyCode === 38 && $scope.previewIndex > 0)
            offset = -1;
        else if (e.keyCode === 40 && $scope.previewIndex < $scope.events.length -1 )
            offset = 1;

        $scope.previewIndex += offset;
        var eventId = $scope.events[$scope.previewIndex].uuid;
        $scope.showEvent(eventId);
        e.preventDefault();
    }
};

$scope.showEvent(eventId) 将获取具有给定 ID 的项目并将其显示在页面的另一部分.在执行另一个操作(例如单击按钮)之前不会更新的部分.是否可以强制页面更新?

$scope.showEvent(eventId) will take the item with given ID and display it in another part of the page. Part that is not update until another action is performed, like clicking a button. Is it possible to force the page update?

这是一个重现的小提琴:http://jsfiddle.net/gM2KF/1/如果单击该按钮,计数器会更新.如果您按任意键,则不显示任何内容.但是你再次点击按钮,你看到计数器已经被键盘事件更新了,但没有显示.

Here's a fiddle that reproduces: http://jsfiddle.net/gM2KF/1/ If you click on the button, the counter is updated. If you press any key, nothing shows. But you click again on the button, you see the counter has been updated by the keyboard event, but didn't show.

推荐答案

如果您正在收听非角度事件:

If you are listening to non-angular events:

element.on('keydown', function(e){
    scopeInit[attrs.keyCapture].apply(null, [e]);                
});

然后,要更新范围,您需要调用scope.$apply:

Then, to update the scope, you need to call scope.$apply:

element.on('keydown', function(e){
    scopeInit[attrs.keyCapture].apply(null, [e]); 
    scope.$apply();               
});

这将启动一个有角度的 $digest 循环并允许绑定更改.

This will kick off an angular $digest cycle and allow changes to bind.

这篇关于范围更新后如何更新 angularjs 页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆