difference between setTimeout in javascript and $timeout service in angularjs

后端 未结 2 715
北恋
北恋 2020-12-05 10:15

Iam new to angular framework.Here is my scenario where, I want to change my $scope.variable after a period of time so i used javascript setTimeout method.

2条回答
  •  無奈伤痛
    2020-12-05 10:46

    Any AngularJS scope variable when handled from outside (including ajax) needs a $apply().

    $timeout() takes care of the current scope and runs in the same digest cycle after all the change detection is done.

    One beauty of $timeout() that I recently discovered is, if you do not pass the time parameter, it will wait for the DOM completion.

    So,

    $timeout(function(){
      console.log("show after directive partial loaded")
    }); //note, no time parameter
    

    Run this code in a directive and the timeout callback function will be fired once the partial has been loaded by the directive

    Hope this helps.

提交回复
热议问题