Home > Web Front-end > JS Tutorial > body text

Directive in AngularJS implements lazy loading_AngularJS

WBOY
Release: 2016-05-16 15:18:15
Original
1446 people have browsed it

So-called lazy loading usually means loading until user interaction. How to implement lazy loading?

Three aspects need to be clarified:

1. Which attribute of the html element requires lazy loading?
2. Which field of the data source needs to be lazy loaded?
3. What events trigger lazy loading?

The page performance of the customized Directive is roughly as follows:

<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> 
Copy after login

Above,
● delay-bind represents a field value to be taken out from the data source
● The attribute table is the html element attribute, and the attribute is assigned a delayed value
● Trigger means triggering lazy loading through that event

Directive code is roughly as follows:

//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);
}()); 
Copy after login

Above, the $interpolate service is used in the compile method. The $interpolate service can first compile and cache the attribute value of a field in the data source through $interpolate(tAttrs.delayBind), in post-link, which is here In the post function, when the event that causes delayed loading is triggered, the $interpolate service starts to compile and assign the value to an attribute of the html element.

The above is related to implementing lazy loading for Directive in AngularJS. I hope it will be helpful to everyone.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template