欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

AngularJS中的Directive實(shí)現(xiàn)延遲加載

 更新時(shí)間:2016年01月25日 14:13:18   作者:Darren Ji  
延遲加載通常是直到用戶交互時(shí)才加載,那么如何實(shí)現(xiàn)延時(shí)加載的呢?下面通過本文一起學(xué)習(xí)AngularJS中的Directive實(shí)現(xiàn)延遲加載,對angularjs延時(shí)加載相關(guān)知識感興趣的朋友一起學(xué)習(xí)吧

所謂的延遲加載通常是:直到用戶交互時(shí)才加載。如何實(shí)現(xiàn)延遲加載呢?

需要搞清楚三個(gè)方面:

1、html元素的哪個(gè)屬性需要延遲加載?
2、需要對數(shù)據(jù)源的哪個(gè)字段進(jìn)行延遲加載?
3、通過什么事件來觸發(fā)延遲加載?

自定義的Directive的頁面表現(xiàn)大致是這樣:

<ul>
<li ng-repeat="cust in customers"
delay-bind="{{::cust.street}}"
attribute="title"
trigger="mouseenter">
<a delay-bind="{{::cust.url}}"
attribute="href"
trigger="mouseenter">
{{cust.name}}
</a>
</li>
</ul>
<div>Total Cusotmers: {{::customers.length}}</div> 

以上,
● delay-bind表示要從數(shù)據(jù)源中取出的某個(gè)字段值
● attribute表是html元素屬性,對該屬性延遲賦值
● trigger表示通過那個(gè)事件來觸發(fā)延遲加載

Directive代碼大致如下:

//interpolate的存在允許one-time一次性綁定
(function(){
var delayBindWithCompile = ['$interpolate', function($interpolate){
var compile = fucntion(tElem, tAttrs){
//delay-bind="{{::cust.street}}"
//這里返回的是一個(gè)函數(shù),也就相當(dāng)于針對street屬性的編譯開始,相當(dāng)于把編譯的功能先緩存在這里
var interpolateFunc = $interpolate(tAttrs.delayBind);
//重新設(shè)置delayBind的屬性值,這時(shí)候DOM還沒有加載呢
tAttrs.$set('delayBind', null); //相當(dāng)于清除屬性值
return {
pre: function(scope, elem, attrs){
},
post: function(scope, elem, attrs){
//trigger="mouseenter"
elem.on(attrs.trigger, function(event){
//attribute="title" 這里title是表示真正要延遲更新的屬性
var attr = atts.attribute,
val = interpolateFunc(scope); //編譯真正執(zhí)行
if(attr && !elem.attr(attr)){
elem.attr(attr, val);
}
});
}
}
};
return {
restrict: 'A',
compile: compile
}
}];
angular.module('directivesModule')
.directive('delayBind', delayBindWithCompile);
}()); 

以上,compile方法中用到了$interpolate服務(wù),$interpolate這個(gè)服務(wù)首先可以通過$interpolate(tAttrs.delayBind)把數(shù)據(jù)源某個(gè)字段的屬性值先編譯緩存起來,在post-link,也就是這里的post函數(shù)中,當(dāng)觸發(fā)引起延遲加載的事件,再讓$interpolate服務(wù)開始編譯把值賦值給html元素的某個(gè)屬性。

以上所述是針對AngularJS中的Directive實(shí)現(xiàn)延遲加載的相關(guān)內(nèi)容,希望對大家有所幫助。

相關(guān)文章

最新評論