0

I have an AngularJS directive that binds to the scroll event:

angular.element($window).bind('scroll',function()
{
});

It's used to update the class of a fixed element when it reaches the bottom of the page.

The problem I have is that when a function fires new elements are drawn and the page grows longer. When scrolling again this is detected properly and the element updates it's class correctly, but until the scroll event fires it looks wrong.

Is there a way to bind the directive to also fire when new elements are drawn to the DOM as well as to scroll?

2 Answers 2

1

How are new elements added to the dom? There's multiple ways to attack this depending on how. Let's say their being rendered via an ng-repeat. For each element attach a new directive (via class, attribute, etc....) and then in the directives controller fire the event you require. Something like:

<div data-ng-repeat="item in items" class="myDirectiveName">...</div>

Then in your directive:

.directive("myDirectiveName", function(){
    return {
        restrict: 'C',
        link: function(scope){
            //fire event
            scope.$emit("newElementAdded", element);
        }
    };
})

edit

If you only want it to fire on the last one, you can do a check

link: function(scope){
    if(scope.$last){
        ...
    }
}

Ng-repeats come with a few things attached to their scopes that you can use, $last, $first etc... check it out here: https://docs.angularjs.org/api/ng/directive/ngRepeat

Sign up to request clarification or add additional context in comments.

3 Comments

That should work, the results are part of an ngRepeat. New results are added when a 'Load x more' button is used which will add 10 results at a time. When 10 results are added together the directive will then presumably be fired 10 times in quick succession. Is there an option that restricts it so it only fires once when the 10 elements are added (after the last element)
I was just playing around with $last, but it still seems to be firing every time something is added. Presumably because 10 rows are added at once, it draws 10 rows and each time something is drawn it's the new last item?
My bad - I'd been using scope.$watch($last). Your method works perfectly, thanks!
0

Directly listening to events with bind(or on) will not cause a digest cycle in angular. You will need to call $apply on the scope to make sure all watchers are called.

Also, depending on if you add the elements manually to the DOM you will need to use the $compile service to have angular parse and execute all directives in the elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.