WJA
WJA

Reputation: 7004

How to trigger a function when scrolled to a specific point in Angular?

I am not looking for a ngInfiniteScroll solution (I don't want to use jQuery).

My page is divided into three sections

<section id="A" ng-init="initA()">
 <!-- Content A -->
</section>

<section id="B" ng-init="initB()">
 <!-- Content B -->
</section>

<section id="C" ng-init="initC()">
 <!-- Content C -->
</section>

How do I trigger the functions initA(), init(B), init(C) when the user scrolls down to the relevant section? That is, upon page load, nothing is loaded. But then once the user starts scrolling down the initX() is being triggered?

Upvotes: 1

Views: 886

Answers (1)

Kursad Gulseven
Kursad Gulseven

Reputation: 2008

You can write a directive for that. See this fiddle: http://jsfiddle.net/6683ppmx/1/

var myApp = angular.module('myApp',[]);

myApp.directive('dSec', function($window) {
  return {
    link: function(scope, elm, attr, ctrl) {
        scope.initialScroll[attr.id] = elm.prop('offsetTop');
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= scope.initialScroll[attr.id]
                    && !scope.hitScroll[attr.id]) {
                 console.log("Scroll to --> ", attr.id);
                 scope.hitScroll[attr.id] = true;
             }
        });
    }
  };
});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.initialScroll = {};
    $scope.hitScroll = {};
}

Upvotes: 1

Related Questions