Angularjs在没有超时的情况下无法正常工作的情况

时间:2013-12-13 11:05:53

标签: angularjs timeout

我在angularjs中遇到的情况很少,只有超时才能解决问题。我真的很想了解为什么会发生这种情况以及如何解决这个问题。

示例:

opLibrary.directive('opClick', function($parse, $location, $timeout, opDebug) {
    return function(scope, element, attrs) {
        var action = attrs.opClick.substring(0, 1) == '/' ? attrs.opClick : $parse(attrs.opClick);
        var event = opDebug.desktop ? 'mousedown' : 'touchstart';
        element.bind(event, function(e) {
            e.preventDefault();
            $timeout(function() {
                if (angular.isFunction(action)) action(scope);
                else $location.path(action);
            }, 0);
        });
    }
});

没有超时$ location.path只是没有触发

$.getScript('//connect.facebook.net/en_UK/all.js', function(){
    FB.init({
        appId: 'xxx',
    });

    $timeout(function() {
        $scope.fbInitComplete = true;
    }, 0);
});

没有超时视图不会根据fbInitComplete更改进行更新,但它会在视图更改之前更新,就像变量的值确实发生更改一样,但是范围没有捕获它

1 个答案:

答案 0 :(得分:3)

使用$scope.apply代替超时:

scope.$apply(function() {
    if (angular.isFunction(action)) action(scope);
    else $location.path(action);
});

原因:您必须在异步完成某些操作时通知angular,例如执行ajax调用时$http为您执行$scope.$apply

相关问题