Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a few things that are probably a good idea (depending on your exact use case). Firstly, a few non-Angular-specific ones:</p> <ul> <li><p>Use a "debounced" version of the listener to the scroll event, so that the function only executes once the user has stopped scrolling. You can use <a href="http://lodash.com/">lodash</a>/<a href="http://underscorejs.org/">underscore</a> library for this.</p> <pre><code>var debounced = _.debounce(function() { .... }, 500); // Executes 500ms after last call of the debounced function. angular.element($document).on('scroll', debounced); </code></pre></li> <li><p>Use a library to determine position/visibility of any element. <a href="http://verge.airve.com/">verge.js</a> is a small lightweight library I've found for this. One way of using this is:</p> <pre><code>var visible = verge.inViewport(element); </code></pre> <p>But depending on what exactly you want to treat as "visible", you might need to change this.</p></li> <li><p>Keep track of what is visible / not visible at every event (as you have a function "atNewArticle", which suggests you only want it called when an item comes into view). So you'll need to create an array of visible elements, and test it on scroll.</p> <pre><code>var index = visibleElements.indexOf(scope.scrollItem); </code></pre></li> </ul> <p>The Angular-specific point: </p> <ul> <li><p>Pass 2 options to the directive. 1) the callback function when a new item comes into view, and 2) the article item itself, so it can be passed back to the callback.</p> <pre><code>scope: { scroll: '&amp;', scrollItem: '=' } </code></pre> <p>These can be used as: </p> <pre><code>&lt;div ng-repeat="article in articles" class="block" scroll="atNewArticle(item)" scroll-item="article"&gt; </code></pre> <p>This gives the directive's scope a variable <code>scrollItem</code>, and a function <code>scroll</code>. So the directive can call, at the appropriate point:</p> <pre><code>scope.scroll({item:scope.scrollItem}); </code></pre> <p>You should note the syntax of this: it's an key-object map.</p></li> </ul> <p>You can see all this in action at <a href="http://jsfiddle.net/Pb8t4/4/">http://jsfiddle.net/Pb8t4/4/</a></p> <p>Edit: updated the link to a jsfiddle that includes a call to <code>scope.$apply</code> so that any changes are properly noticed by Angular.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload