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

Verification upon button press for a form

Currently, I have a form with multiple textboxes that are being validated using the Required Field Validator. However, there is also a captcha control that is not getting validated. I can validate it using JavaScript though. At the moment, an alert pops u ...

Activate the extended view of a Material-UI Accordion

When using Accordions to display editable entities, we often want to keep modified entities in the expanded state. Currently, we have had to duplicate functionality by lifting up the expanded state into the accordion wrapper to prevent any controlled <- ...

The expandable row remains open even after filtering the table with JavaScript

An expandable row in the table displays details of rows. I have implemented a JavaScript search and filter function to find specific row content. However, when using the search filter, it successfully shows results but does not expand the details as intend ...

There was an error in the search: [parse_exception] The search source could not be parsed. A field name was expected, but instead [

I'm experiencing a query parsing exception while utilizing JavaScript for Elasticsearch configuration found in elastic.js file. Results are obtained when the filtered part is removed. However, upon adding it back, an exception occurs. var client = r ...

Create a new array by applying a filtering function to the provided data in JavaScript using React

I am a beginner in the world of React. I have an object containing an array (Map) as follows: "POSSIBLE_UPDATE_OPTIONS": { "Process": ["confirm"], "Confirmed": [ "Process", ...

The AngularJS component materializes almost instantaneously

Using AngularJS, I have developed an application where a certain section of code is displayed after the page loads for a split second: <div class="col-sm-4" data-ng-repeat="user in users"> <div class="card"> ...

What is the reason for being able to access `$scope` and `this` using the controller as syntax?

Creating an Angular controller with the controller as syntax: <body ng-controller="ctrl as myCtrl"> <p>Accessed via scope resolution: {{ foo }} </p> <p>Accessed via controller resolution: {{ myCtrl.foo }}</p> </body> ...

Number entered isn't visible in Bootstrap modal window

Can anyone help me troubleshoot why the value "APno" is not appearing next to "Appointment Number" in a Bootstrap modal despite the modal showing up? This is my code: Form <form method="POST> Appointment Number:<br> <input type="n ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

Showing a div with a smooth fade-in effect while switching its display property to inline using jQuery

Currently, I am working on a project that involves implementing a "side pop up". To ensure it doesn't flicker like it does with jQuery's "hide()" method, I want to start by setting the display property to none using CSS. My main question is: - Ho ...

Binding arguments to child functions within Vue components

When working with React, it's a common practice to bind parameters for child components in the following manner: <Child onChange={e => doThing(complex.variable.inParentScope[3], e.target.value)} foo="bar" /> In Vue, I want to ach ...

What is the best way to create a backup copy of my project using git?

To ensure the safety of my project, I took the necessary steps to back it up. First, I initialized a repository using git init Following that, I committed all files by executing git add . git commit -am "first commit" Now, the next step involves pushin ...

The variable _spPageContextInfo has not been defined, resulting in a ReferenceError

The code in my JavaScript file looks like this: var configNews = { url:_spPageContextInfo.webAbsoluteUrl, newsLibrary: 'DEMONews', listId: '' }; // Attempting to retrieve the List ID $.ajax({ url: configNews.url + "/_a ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

Steps for embedding a font in a .pptx file

While working on creating a .pptx file using ASPOSE.Slides, I encountered some issues with embedding fonts. As an alternative option, I am looking for suggestions on how to embed custom fonts in a .pptx file using Apache POI or other methods. If you have ...

Obtaining data from JSON arrays

My current challenge involves extracting data from the following link: and storing it in my database. However, I am encountering difficulties with manipulating the array in order to retrieve the last unix datetime. Despite multiple attempts to extract th ...

Make a JSONP request with the MIME Type set to text/plain

I've been attempting to utilize JSONP for fetching a feed from a different domain. Despite knowing that the content type should ideally be JSON or JavaScript, it is currently set as text/plain and unfortunately, I lack control over the server settings ...

The interface vanishes upon the integration of TinyMCE into the module

Currently, I am working on a project using Angular-fullstack and attempting to integrate ui-TinyMCE. However, I encountered an issue when I made the following changes: angular.module('academiaUnitateApp') .controller('NewEntryCtrl', ...

"Upload a video file and use JavaScript to extract and save the first frame as an image

I have a webpage where users can upload a video file, and the page will generate a thumbnail based on a timestamp provided by the user. Currently, I am focusing on generating the thumbnail from the FIRST frame of the video. Here is an example of my progr ...