区别总结如下:
directive中执行的$evalAsync
, 会在angular操作DOM之后,浏览器渲染之前执行。
controller中执行的$evalAsync
, 会在angular操作DOM之前执行,一般不这么用。
而使用$timeout
,会在浏览器渲染之后执行。
以下是测试DEMO:
01 | //创建一个app module |
02 | var app = angular.module( "Demo" , [] ); |
03 | |
04 | //测试 $timeout() 和 $evalAsync() 函数的输出时间顺序 |
05 | app.directive( |
06 | "bnTiming" , |
07 | function ( $timeout ) { |
08 | |
09 | // 本地scope的一个js事件绑定@camnpr |
10 | function link( $scope, element, attributes ) { |
11 | |
12 | $timeout( |
13 | function () { |
14 | console.log( "$timeout 1" ); |
15 | } |
16 | ); |
17 | |
18 | $scope.$evalAsync( |
19 | function ( $scope ) { |
20 | console.log( "$evalAsync" ); |
21 | } |
22 | ); |
23 | |
24 | $timeout( |
25 | function () { |
26 | console.log( "$timeout 2" ); |
27 | } |
28 | ); |
29 | } |
30 | |
31 | // 返回这个指令的配置@camnpr |
32 | return ({ |
33 | link: link |
34 | }); |
35 | } |
36 | ); |
输入结果如下:
$evalAsync
$timeout 1
$timeout 2