所謂的延遲加載通常是:直到用戶交互時才加載。如何實現(xiàn)延遲加載呢?
需要搞清楚三個方面:
1、html元素的哪個屬性需要延遲加載?
2、需要對數(shù)據(jù)源的哪個字段進(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ù)源中取出的某個字段值
● attribute表是html元素屬性,對該屬性延遲賦值
● trigger表示通過那個事件來觸發(fā)延遲加載
Directive代碼大致如下:
//interpolate的存在允許one-time一次性綁定(function(){var delayBindWithCompile = ['$interpolate', function($interpolate){var compile = fucntion(tElem, tAttrs){//delay-bind="{{::cust.street}}"http://這里返回的是一個函數(shù),也就相當(dāng)于針對street屬性的編譯開始,相當(dāng)于把編譯的功能先緩存在這里var interpolateFunc = $interpolate(tAttrs.delayBind);//重新設(shè)置delayBind的屬性值,這時候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這個服務(wù)首先可以通過$interpolate(tAttrs.delayBind)把數(shù)據(jù)源某個字段的屬性值先編譯緩存起來,在post-link,也就是這里的post函數(shù)中,當(dāng)觸發(fā)引起延遲加載的事件,再讓$interpolate服務(wù)開始編譯把值賦值給html元素的某個屬性。
以上所述是針對AngularJS中的Directive實現(xiàn)延遲加載的相關(guān)內(nèi)容,希望對大家有所幫助。
新聞熱點
疑難解答