Updating ngRepeat Array Data in AngularJS using Events

I'm currently in the process of transitioning my jQuery application to AngularJS.

One of the tasks I need to accomplish involves updating the Data Array whenever a scroll event occurs. How can I achieve this?

Here is the existing jQuery code at Plunker: http://plnkr.co/edit/jdwxH5pmyecuWTsrutrO?p=preview

When you scroll within the div, a list displaying the index of visible elements is shown.

What I aim to do is create a directive or filter (ng-check-visibility) for the ng-repeat element, like so:

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

This directive should modify the item by assigning the value item.visible=true when the element is visible, and false otherwise.

Can this be achieved with Angular? Any suggestions?

Answer №1

Here is a directive approach to achieve this functionality:

  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>  

Check out the plunkr example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to export JavaScript module

In my JavaScript project, I have a module named utilities stored in a file called utilities.js. This module contains basic functions that I want to keep hidden from the global namespace. I know that in order to achieve this, I need to create a module, expo ...

How to redirect in Next.js from uppercase to lowercase url

I'm trying to redirect visitors from /Contact to /contact. However, following the instructions in the documentation results in an endless loop of redirects. This is my attempted solution: // next.config.js async redirects() { return [ { ...

What is the process to transfer data from JavaScript to HTML within a Laravel environment?

I am attempting to transfer a value from JavaScript to HTML as a variable. In order to do this, I am retrieving the value from a Laravel PHP controller. JavaScript $("ul.nav-tabs > li > a").click(function() { var id = $(this).attr("href").repla ...

Toggle the visibility of a div based on the id found in JSON data

I am looking to implement a JavaScript snippet in my code that will show or hide a div based on the category ID returned by my JSON data. <div id="community-members-member-content-categories-container"> <div class="commun ...

Ensuring uniqueness of group by values in JavaScript when a textbox loses focus

Make sure the first column is unique by preventing duplicate entries in the second column textbox using JavaScript on blur event. <table rules="all" class="table table-bordered"> <tbody> <tr> < ...

Obtaining data via a URL and then displaying it in HTML with node.js and express.js

I am currently working on a JavaScript file where I am utilizing Node's 'request' module to make API calls, process data, and return an HTML response to the user. If you're interested, you can take a look at this snippet from my file. ...

Ensuring a dependable detection of WebSocket connection status

I've been researching how to create a dependable method for recovering a WebSocket connection. After exploring various options, I discovered that one approach involves sending heartbeats (ping/pong) to the server and monitoring if the entire pong is ...

Ways to modify the color of text in a hyperlink?

When working with hyperlink generation like the code snippet below, the typical blue color can be less than ideal. How can I dynamically change the font color of this hyperlink using JavaScript? $element.html(indicator.link(url)); ...

Using special symbols in HTML5 data attributes

Is it feasible to locate all DOM elements using jQuery with wildcard characters in the attribute name? Take into consideration the following HTML code: <input id="val1" type="text" data-validate-required data-validate-minlength ...

Swap information in one array with information from a different array

I am working with two arrays: const data = [ { id: 0, identifier: 'free-2020', name: '<I18nText id="pricing.plans.name.free" />', planTitle: 'free', price: '00', ...

Choosing various data using Ajax

I am currently in the process of extracting various pieces of data from my insert.php page, including the post id, username, and user id. I intend to include other selected data as well. However, when trying to echo out multiple queries, all the informatio ...

Error occurs when using $window.history.pushState in the presence of $location

Take a look at this Plunkr example that illustrates the issue I am facing: http://plnkr.co/edit/c0AEXBXAHz4ZqH4kIXyN. The error occurs when using $window.history.pushState with $location in the dependency injector and providing a non-empty string as the ...

An AJAX request will only occur if there is an alert triggered on a particular computer

Here's an interesting issue I encountered with my company's CMS newsletter system. It seems that the AJAX call to send an email works flawlessly in all modern browsers and operating systems, except for one client. This particular client is using ...

Guide to organizing an express.js project structure:

When working with an Express.js application, what are the typical strategies for breaking up and modularizing the app.js file? Do developers usually keep everything in a single file, or is there a common convention for splitting it into smaller modules? ...

Tips for creating a dynamic curved SVG path

I'm looking to draw a black border only along the inside of this SVG. I've tried adding stroke and setting the stroke-width, but that applies the border to the entire SVG. Is there a way to limit the stroke to a certain point within the SVG? d ...

Despite the onsubmit returning false, the submit operation still goes through

I seem to have hit a roadblock yet again. My registration form incorporates three JavaScript functions which display the desired output when triggered by an onchange event within my HTML form. These functions generate a Bootstrap alert while the user is co ...

What is the benefit of using an IIFE in this particular way when constructing a JavaScript library?

Many libraries I've seen use a similar style to define their structure. Upon further inspection, I've noticed that the first self-invoking function is often related to Require.js or AMD systems, with 'factory' as an argument. My curiosi ...

Exploring the crossroads of MongoDB, Mongoose, and Node.js: An in-depth look

Searching for ways to retrieve references in MongoDB using Node.js and Mongoose. After reading the documentation, I discovered that there are two options available: Manual References or DBRefs. Given that Manual References are recommended, I proceeded to ...

Utilizing only select functions from lodash can be more beneficial than installing the entire library, as it reduces the amount of unnecessary dependencies

While working on my project, I incorporated underscore.js for its functionality. However, I recently discovered the need for Lodash's fill function. The idea of adding Lodash to my project seems excessive due to overlapping features with underscore.js ...

Can you explain the significance of the output "Object[...]" displayed in Firebug?

Currently, I am logging an object within an AngularJS directive. Specifically, I am focusing on the parameters of the link() function of the directive. Here is the code snippet: link: function(scope, element, attrs) { console.log(attrs) } Upon checking ...