简体   繁体   中英

How to specify execution order in (asynchronous) Angular/Javascript

I have a custom directive (this is just a simplified example). When the directive is clicked, a variable is updated and a function is executed. Both the variable and the function is from the parent scope, accessed via two-way binding and method/behavior binding respectively.

In some cases the parent scope might overrule the directive and force the variable to be a different value than the one set by the directive.

My problem is that the function is called before the variable is updated, probably because the asynchronous behaviour. That means that the variable gets overwritten by the directive.

Is there some way to force the function to be called after the variable has been updated?

This is from the directive's link function:

element.bind('click', function(){
    scope.val = 'someValue'; // This should alway be executed first
    scope.directiveClicked(); // This should always be executed last
});

The variable and method are accessed like this:

scope: {
    val: '=value',
    directiveClicked: '&onDirectiveClick'
}

Turned out that it was not called in the wrong order after all, but somehow the updated value was not displayed/stored. Adding a scope.$apply() before notifying the parent function did the trick.

element.bind('click', function(){
    scope.val = 'someValue'; 
    scope.$apply();
    scope.directiveClicked(); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM