zoukankan      html  css  js  c++  java
  • 在AngularJS中实现一个延迟加载的Directive

    所谓的延迟加载通常是:直到用户交互时才加载。如何实现延迟加载呢?

    需要搞清楚三个方面:

    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元素的某个属性。

  • 相关阅读:
    Failed to start mysqld.service: Unit not found
    Nginx转发前后端分离跨域引发的问题-转发请求header头中含有下划线,无法转发取值
    云上Centos7新硬盘挂载流程
    马哥教育第二阶段考试
    Linux集群准备-同步
    Lucene查询语法
    权限系统设计
    docker compose thinkphp5.1 lnmp环境搭建加项目部署全过程
    docker compose 的使用
    [转载]PHP-FPM
  • 原文地址:https://www.cnblogs.com/darrenji/p/5156991.html
Copyright © 2011-2022 走看看