20.實(shí)現(xiàn)AngularJS渲染完畢后執(zhí)行腳本
目前要實(shí)現(xiàn)這樣一個(gè)功能:使用bootstrap-select和AngularJS實(shí)現(xiàn)動(dòng)態(tài)下拉表單。
AngularJS用于實(shí)現(xiàn)下拉菜單的內(nèi)容渲染,內(nèi)容通過(guò)AJAX獲得,代碼如下:
<select class="selectpicker" data-ng-model="queryForm.type">
<option value="{{ type }}" data-ng-repeat="type in types">{{ type }}</option>
</select>
<script>
$http({
url: '/types',
method: 'GET',
}).success(function(response){
$scope.types = response;
});
</script>
bootstrap-select用做下拉表單樣式渲染,select標(biāo)簽內(nèi)容改動(dòng)后,需要顯示調(diào)用refresh指令進(jìn)行重新渲染呢,例如
$('.selectpicker).selectpicker('refresh');
現(xiàn)在問(wèn)題來(lái)了,如何實(shí)現(xiàn)在AngularJS渲染完DOM之后調(diào)用bootstrap-select進(jìn)行select表單的重新渲染呢?
百度了一下,發(fā)現(xiàn)絕大部分人都是使用通過(guò)自定義AngularJS指令+link函數(shù)實(shí)現(xiàn)。果斷不能接受!殺雞豈用牛刀?
仔細(xì)想了一下,發(fā)現(xiàn)我們可以通過(guò)setTimeout很優(yōu)雅地實(shí)現(xiàn)這個(gè)功能。JavaScript代碼如下:
$http({
url: '/types',
method: 'GET',
}).success(function(response){
$scope.types = response;
$timeout(function(){
$('.selectpicker').selectpicker('refresh');
},0);
});
主要原理就是利用了setTimeout函數(shù)所處的隊(duì)列只會(huì)在調(diào)用棧清空后才會(huì)被執(zhí)行。
也就是說(shuō),當(dāng)setTimeout執(zhí)行時(shí),AngularJS的DOM渲染已經(jīng)被執(zhí)行完畢,并且調(diào)用棧已經(jīng)清空了。此時(shí)bootstrap-select獲得的DOM節(jié)點(diǎn)一定是最新的。
大家都采用的做法不一定都是最優(yōu),特別像一些殺雞焉用牛刀的實(shí)現(xiàn),遇到他們時(shí),你就該好好想想了。