所謂的延遲加載通常是:直到用戶交互時才加載。如何實現延遲加載呢?
需要搞清楚三個方面:
1、html元素的哪個屬性需要延遲加載?
2、需要對數據源的哪個字段進行延遲加載?
3、通過什么事件來觸發延遲加載?
自定義的Directive的頁面表現大致是這樣:
<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表示要從數據源中取出的某個字段值
● attribute表是html元素屬性,對該屬性延遲賦值
● trigger表示通過那個事件來觸發延遲加載
Directive代碼大致如下:
//interpolate的存在允許one-time一次性綁定 (function(){ var delayBindWithCompile = ['$interpolate', function($interpolate){ var compile = fucntion(tElem, tAttrs){ //delay-bind="{{::cust.street}}" //這里返回的是一個函數,也就相當於針對street屬性的編譯開始,相當於把編譯的功能先緩存在這里 var interpolateFunc = $interpolate(tAttrs.delayBind); //重新設置delayBind的屬性值,這時候DOM還沒有加載呢 tAttrs.$set('delayBind', null); //相當於清除屬性值 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); //編譯真正執行 if(attr && !elem.attr(attr)){ elem.attr(attr, val); } }); } } }; return { restrict: 'A', compile: compile } }]; angular.module('directivesModule') .directive('delayBind', delayBindWithCompile); }());
以上,compile方法中用到了$interpolate服務,$interpolate這個服務首先可以通過$interpolate(tAttrs.delayBind)把數據源某個字段的屬性值先編譯緩存起來,在post-link,也就是這里的post函數中,當觸發引起延遲加載的事件,再讓$interpolate服務開始編譯把值賦值給html元素的某個屬性。