1

I've come to few situations in angularjs where only timeout solves the problem. I'd really like to understand why this happens and how to solve this.

Examples:

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);
        });
    }
});

without timeout $location.path just doesn't trigger

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

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

without timeout view is not updated based on fbInitComplete change, though it updates just before view change as if value of the variable did change, but scope did not catch it

1 Answer 1

3

Use $scope.apply instead of timeout:

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

Reason: You must notify angular when something is done asynchronously, for example when performing ajax call ($http does $scope.$apply for you).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! That explains everything :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.