Matt McDonald
Matt McDonald

Reputation: 5050

AngularJS directive that binds to multiple events

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?

Upvotes: 0

Views: 1332

Answers (2)

Mathew Berg
Mathew Berg

Reputation: 28750

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

Upvotes: 1

Zerot
Zerot

Reputation: 196

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.

Upvotes: 0

Related Questions