I'm trying to fully grasp the concept of the AngularJS link function
Here's an example of a custom lazy load directive:
script.js:
//Code
angular.module('app', []);
angular.module('app').controller('mainCtrl', function($scope) {
$scope.items = [2,5,23,253];
});
angular.module('app').directive('myLazyRender', function() {
return {
restrict: 'A',
transclude: 'element',
priority: 900,
link: function(scope, el, attr, ctrl, transclude) {
var hasBeenShown = false;
var unwatchFn = scope.$watch(attr.myLazyRender, function(value) {
if(value && !hasBeenShown) {
hasBeenShown = true;
transclude(scope, function(clone) {
el.after(clone);
});
unwatchFn();
}
})
}
}
})
angular.module('app').directive('echo', function() {
return {
priority: 1300,
link: function() {
console.log('echo');
}
}
})
index.html:
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8f8282999e999f8c9dc08e9e9eaddec3dcc3dc">[email protected]</a>" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a4845455e595e584b5a6a19041b041b">[email protected]</a>" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c434a58414c5f03475e6d1c031e031d005f4e0319">[email protected]</a>" data-semver="1.3.0-rc.4" src="https://code.angularjs.org/1.3.0-rc.4/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
<h1>Hello Plunker!</h1>
<div my-lazy-render="showit" echo ng-repeat="item in items">
{{item}}
</div>
<button class="btn btn-primary" ng-click="showit = true">Render Content</button>
</body>
</html>
I have come across documentation that explains the purpose of the link function in AngularJS, which is to create an event listener to handle events
If this is the case, could someone shed light on the role of this event listener and the types of events it can listen to when transcluding an element with ‘transclude: ‘element’ in this particular example.
Is there a specific DOM event for binding the item content?
In the provided example, when I click on the Render Content button, the content of item gets loaded.