事件绑定的方式AngularJS? [英] Event Bindings The AngularJS Way?

查看:108
本文介绍了事件绑定的方式AngularJS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,我知道,它被认为是不好的做法,与AngularJS工作时做任何DOM操作的控制器,你应该使用指令和$余地的东西,但有关事件的结合呢?从外观上来看,这也是皱眉考虑所有内置的事件指令一样ngClick,ngMousedown,ngMouseenter,等...但如果​​是这样的话,那么我有一块code,我不要的'知道该怎么做AngularJS方式。

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.

我建立的应用程序有无限滚动,它是这片code(即目前生活在一个控制器)来实现:

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();
    }
});

这允许用户滚动页面并且当网页获取到存储具有无限滚动的数据元素的底部,它触发关闭功能装载更多的数据。现在,我没有做任何DOM操作,所有功能只需更新连接到$范围的数据,我让AngularJS做DOM更新,但是是有这个活动针对与AngularJS最佳实践的结合?如果是的话我怎么会是能够做到这一点的方式AngularJS(我不认为一个指令会在这种情况下工作,因为我不认为这是可能的指令附加到文档对象)?

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)?

推荐答案

我不认为目前做这类事件绑定的一个AngularJS方式。添加所有丢失的事件,原生支持是出头这是正在进行中,据我所知,但它不是在任何稳定版本尚未公布。

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();
    }
);

这是因为你在处理来自AngularJS之外的事件。在$应用件事确保AngluarJS被告知可能产生作为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.

这篇关于事件绑定的方式AngularJS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆