The AngularJS ng-repeat filter {visible: true} does not respond to changes in properties

var myApp = angular.module('myApp', ['infinite-scroll']);

myApp.controller('DemoController', function($scope, $timeout, $rootElement) {
    $scope.$rootElement = $rootElement;
    $scope.$timeout= $timeout;

    $scope.init = function(){
        $scope.posts = [
            {id: 1},
            {id: 2},
            {id: 3},
            {id: 4},
            {id: 5},
            {id: 6},
            {id: 7},
            {id: 8},
        ];

        window.posts = $scope.posts;
        _.each($scope.posts, function(post){
            post.visible = true;
        });
        //$scope.posts[1].visible = false;
    };

    $scope.is_visible = function(item) {
      return item.visible;
    };

    $scope.hide_topmost_items = function(){
        _.each($scope.posts, function(post){
            var elem = $('#post_' + post.id);
            if (elem.position().top + elem.height() + 500 < window.pageYOffset){
                post.visible = false;
                window.scrollTo(0, window.pageYOffset - elem.height());
                //elem.hide();
                console.log('#post_' + post.id + ' is hidden now')
            }
        });
    };

    $(window).on('scroll', $scope.hide_topmost_items);

    $scope.loadMore = function() {
        var length = $scope.posts.length;
        var last = $scope.posts[length - 1];
        for(var i = 1; i <= 8; i++) {
            $scope.posts.push({id: i + length});
        }
    };

    $scope.init();
});

https://github.com/scythargon/scythargon.github.io

I am looking to implement a feature that hides elements which are too high above the user's current viewing window. I have tried using jQuery (as seen in the commented out elem.hide(); line), but I want to achieve this in an AngularJS way. I also attempted to create a filter function based on suggestions from various online sources, however, it seems that the visibility of elements is only affected during initialization (not dynamically as intended, even with the commented out $scope.posts[1].visible = false; line).

Answer №1

When you call your $scope.hide_topmost_items() function from outside of Angular using $(window).on('scroll'), it is important to remember to manually trigger $scope.$apply() after making any changes to properties within the $scope object.

$scope.hide_topmost_items = function(){
  _.each($scope.posts, function(post){
    var element = $('#post_' + post.id);
    if (element.position().top + element.height() + 500 < window.pageYOffset){
      post.visible = false;
      window.scrollTo(0, window.pageYOffset - element.height());
      //element.hide();
      console.log('#post_' + post.id + ' has been hidden');
    }
  });

  $scope.$apply(); // Always include this when calling from outside Angular
};

I hope this clarification is useful for you.

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

Steps for launching a browser using Capybara and Selenium

I am completely new to utilizing Capybara and have not had any experience with Selenium in the past. Currently, I am working on a Ruby on Rails project on MacOSX and encountering an issue where the browser window does not open when I execute my test. My te ...

Attempting to confirm the accuracy of a data point within an extensive and interactive online table

I am facing a challenge in verifying a specific value from a large web table because none of the locators are unique and Selenium is unable to find all the elements. I am using Selenium and Cucumber JVM for automation. Below is a snippet of the HTML code ...

Add empty objects to an array using a push function following the Vue JS constructor function

During my learning journey with Vue JS, I encountered an issue while attempting to populate an array with objects using a constructor function and the push method. Surprisingly, in Vue JS, the push function inserts a blank object into the array instead of ...

What is the proper way to access the global `angular` variable in Angular and TypeScript when using AngularJS?

I'm currently integrating an Angular 4 component into a large monolithic AngularJS application. The challenge I face lies in the restrictions of the AngularJS project's build system, which limits me to only modifying the project's index.html ...

Tips for incorporating an HTML file using ng-include in double curly brace syntax {{ }}

Here is the code snippet I am working with: <div ng-repeat="pTabs in child.productTabs" ng-click="toggleProductTab($index)" ng-if="productTabIsActive(pTabs, $index)"> <div ng-repeat="specs in pTab.additionalSpecs"> <p>{{spec ...

Repeated instances in a loop are strictly prohibited

I am facing an issue with AngularJS where I am unable to display JSON data in my HTML. Below is the code I am using: $('.loading').show(); $scope.posts=[]; $http.get("https://api.basebear.com/json/tables/20a3fb1d-42c7-45cb-9440-2c6d5d10403d/r ...

Set a variable to a specific cell within a table

I've been attempting to insert images into a table and have had success so far - clicking cycles through the available options. However, I've encountered an issue where the counter is not cell-specific but rather global. Is there a way to create ...

Get rid of any empty space in the image preview icon

Is there a way to eliminate the white space that appears when mixing landscape and portrait images? I want the images to move up and fill the space, even if they don't align perfectly. Additionally, I would like the images to resize based on the scal ...

Submit your information discreetly

Is there a way to submit a form to an external website without it causing the page to reload? I am working on automatically logging users into their Google account without interrupting their browsing experience. The following code snippet allows me to pr ...

Tips for downsizing a large image to fit into a smaller area

I am working on a page layout that features a small circular navigation element. However, I am facing an issue with fitting a large picture within the boundaries of this small circle without it overflowing and causing alignment problems. Does anyone have ...

How can I efficiently pass a JavaScript object to a function using jQuery syntax?

Recently, I've delved into the world of JavaScript and started exploring object orientation, prototyping, and using objects for all functions and variables. However, there is one aspect that many frameworks like jQuery or extJS have that I struggle wi ...

What is the best way to retrieve the outcome of a node-sqlite3 query beyond the scope of db.get()?

I'm attempting to validate whether the sha256 hash stored in my sqlite database corresponds with the sha256 hash of the password that the user transmitted to my NodeJS server. The Auth() method is meant to deliver either a true or false result. Is the ...

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

Troubleshooting problem: AJAX autocomplete URL returning XML

I found my code reference here: http://example.com/code-reference if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes-> ...

Adjust the size of icon passed as props in React

Below is the component I am working on: import ListItemButton from '@mui/material/ListItemButton'; import ListItemIcon from '@mui/material/ListItemIcon'; import Tooltip from '@mui/material/Tooltip'; const MenuItem = ({data, o ...

Highcharts' labels on the x-axis do not automatically rotate

One issue I am facing is that my custom x-axis labels on the chart do not rotate upon window resize. I would like to have them rotated when the screen size is less than 399px. Check out the code here $(function () { $('#container').highchart ...

What is the reason behind shadow dom concealing HTML elements when viewed in inspect mode?

https://i.stack.imgur.com/UZM7f.png Monday.com has implemented Shadow Dom to protect its source code. How can I work around this limitation? ...

AngularJS radio buttons are interactive HTML elements that allow users

I've been looking for a solution to bind my radio inputs to a model in a simple and clean way, but I haven't found one that works for me yet. In my HTML, I have: <input ng-model="searchByRma" type="radio" name="search-type"> <input ng-m ...

Discovering parent elements far up the DOM hierarchy using jQuery

I'm a bit confused about how to locate an element that is a parent element further up the tree. $('.btn-action').hover( function(){ $(this).find('.product-card').addClass('animated bounce'); }, function(){ ...

Convert the string to a time format of hours and minutes (hh:mm)

I am currently working with an input field that requires a time value to be entered. The format for the Time field is in hh:mm on the 24-hour clock format, such as 7:30, 11:45, 16:10, 19:11, or 22:43. <input id="szReminderTime" type="text" value="" max ...