I'm migrating my jQuery app to AngularJS.

What I need to do, is change the Data Array when a scroll occurred, how can i do this?

I have this code with jQuery at plunk: http://plnkr.co/edit/jdwxH5pmyecuWTsrutrO?p=preview

When you scroll the div, a list with the visible elements index is show.

What I want to do, is to set a directive or a filter (ng-check-visibility) at the ng-repeat element, like:

<div ng-repeat="item in data" ng-check-visibility>
    {{item.name}}
</div>

And this directive change the item setting the value item.visible=true when the element is visible, otherwise, set it to false.

Can I do this with Angular? Any ideas?

share|improve this question
up vote 4 down vote accepted

Here's a way to do it as a directive:

  var app = angular.module('myapp', []);
  app.controller('MainCtrl', function($scope) {

    arr = [];
    for(var i=0; i<500; i++){
      arr.push({id: i, name: 'name'+i});          
    }
    $scope.data = {
      items: arr,
      visible: []
    };
  });

  app.directive('checkVisibility', function() {
    return {
      scope: {
        data: '=checkVisibility'
      },
      link: function(scope, el, attrs) {
        el.scroll( function() {
          var reference_top = el.offset().top;
          var reference_height = el.height();

          var $elements = el.find('.check');

          scope.data.visible = [];
          for(var i=0; i<$elements.length; i++){
            var $element = $($elements[i]);
            var element_top = $element.offset().top;
            var element_height = $element.height();

            if (reference_top < element_top + element_height &&
                reference_top + reference_height > element_top) {
                scope.data.visible.push( i );
            }
          }
          scope.$apply();
        });
      }
    };
  });

--

<body  ng-controller="MainCtrl">
  <div class="outer-panel" check-visibility="data">
    <div class="inner-panel">
      <div ng-repeat="item in data.items" class="check">
        {{item.name}}
      </div>
    </div>
  </div>
  <div id="visibles">
    {{data.visible}}
  </div>
</body>  

plunkr

share|improve this answer
    
Great! Very good idea! – Bruno Croys Felthes May 14 '13 at 20:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.