在AngularJS中實現一個延遲載入的Directive

Darren Ji發表於2016-01-25

 

所謂的延遲載入通常是:直到使用者互動時才載入。如何實現延遲載入呢?

需要搞清楚三個方面:

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元素的某個屬性。

 

相關文章