0

Is it possible to lazy load directives?

Say we have 20 Directives on a single page, and on scroll, if the directive is in viewport it should get rendered.Otherwise no action should take take.

It should behave as lazy loading of images.

Can we achieve it??

Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59

1 Answers1

0

You Question is unspecific but I'm willing to try: Imagine your HTML like that

<div ng-app="app" ng-controller="myCtrl">
<ul id="myList">
    <li ng-repeat="item in data">
        <mydirective item="item"></mydirective>
    </li>
</ul>

the directive is is doing whatever needed for your item

angular.module("mydirective", []).directive("mydirective", function() {
    return {
        templateUrl: 'templates/mytemplate.php',
        replace: false,
        transclude: false,
        restrict: 'A',
        scope: {
            item:        "="
        }
    };
});

The controller would look like that

app.controller("myCtrl", ["$scope", function ($scope) {
    $scope.data = [
        {id: 1, "name": "img1"},
        {id: 2, "name": "img2"},
        {id: 3, "name": "img3"}
    ];

    $("#myList").bind("scrollend", function(e){
        $scope.loadNextElements();
    });

    $scope.loadNextElements = function() {
        // add new elements
        $scope.data.push({id: 4, "name": "img4"});
        $scope.data.push({id: 5, "name": "img5"});
        $scope.data.push({id: 6, "name": "img6"});
        ...
    }
}]);