Event Bindings The AngularJS Way?

2019-05-31 00:45发布

问题:

Ok, so I know that it is considered bad practice to do any DOM manipulation in a controller when working with AngularJS, you should be using directives and $scope for that stuff, but what about event binding? From the looks of it, that is also frowned upon considering all the built-in event directives like ngClick, ngMousedown, ngMouseenter, etc... but if that is the case then I have a piece of code that I don't know how to do the AngularJS way.

The application I am building has infinite scrolling and it is implemented with this piece of code (that currently lives in a controller):

$(document).bind('scroll', function(){
    if(!$scope.loadingIssues && $(window).scrollTop() + $(window).height() >= $('.user-feedback-list').offset().top + $('.user-feedback-list').height()) {
        $scope.loadIssues();
    }
});

This allows the user to scroll the page and when the pages gets to the bottom of the element that is storing the data that has infinite scrolling, it fires off the function to load more data. Now I am not doing any DOM manipulation, all the functions just update data attached to the $scope and I let AngularJS do the DOM updates but is having this event binding against best practices with AngularJS? If so how would I be able to do this in the AngularJS way (I don't think a directive would work in this case since I don't think it is possible to attach a directive to the document object)?

回答1:

I don't think there currently is an AngularJS way of doing this kind of event binding. Adding native support for all the missing events is somethings that's underway, as far as I know, but it's not released in any stable version yet.

So for now we have to do it like you state in your question.

I think, though, that you will need to do this to make it work:

$scope.$apply(
    function() {
        $scope.loadIssues();
    }
);

This is because you're handling the event from outside of AngularJS. The $apply thing makes sure AngluarJS is notified of any model changes and things like that which might occur as a result of your loadIssues() call.