Eliminating an ngRepeat item from the $rootScope array does not automatically result in the item being removed from the html code

Attempting to eliminate an li from a ul using angular. Although the element is successfully removed from the array, AngularJS does not remove the li until it is interacted with, such as being hovered over or clicked. See the code below:

app.js

myApp.run(function($rootScope, appAPIservice){ 
  appAPIservice.getInterests().success(function (response) {
    $rootScope.interests = [];
    if (response.data) {
      var interests = response.data;
      for (var i = 0; i < interests.length; i++) {
        $rootScope.interests.push(interests[i]));
      }
    }
  });
});

index.html

<ul ng-controller="interestsController">   
  <li ng-repeat="interest in interests">
    <a href="#{{interest.link}}">{{interest.parentName}} / {{interest.childName}}</a>
    <button ng-click="deleteInterest($index)"></button>
  </li>
</ul>

controllers.js: Contains the deleteInterest function

myApp.controller('interestsController', function($scope) {
  $scope.deleteInterest = function(arrayIndex) {
          $scope.interests.splice(arrayIndex, 1);
      });
  }
});

When the page loads, the following is displayed:

<ul class="ng-scope" ng-controller="interestsController">   
  <li class="ng-scope" ng-repeat="interest in interests">
    <a href="#/other-link class="ng-binding">Other Parent/Other Child</a>
    <button ng-click="deleteInterest($index)"><i class="icon-close"></i></button>
  </li>
</ul>

The issue arises when clicking the deleteInterest() button. The list item gains the following classes: ng-animate, ng-leave, ng-leave-active. Unfortunately, the item will not be removed from the list until it is hovered over. Only then is it successfully removed from the DOM.

<li class="ng-scope ng-animate ng-leave ng-leave-active" ng-repeat="interest in interests">
  <a href="#/some-link" class="ng-binding">Some Parent / Some Child </a>
  <button ng-click="deleteInterest($index)"><i class="icon-close"></i></button>
</li>

Attempts have been made to resolve this issue by wrapping

$scope.interests.splice(arrayIndex, 1);
in interestsController.deleteInterest with:

$scope.$apply(function(){ 
  $scope.interests.splice(arrayIndex, 1);
}); 

However, an error message stating that $scope.$digest is already in progress is received.

Is there a method to compel AngularJS to remove all ng-leave elements?

Answer №1

Consider these suggestions. Rather than using $scope.$apply, you can try

$timeout(function(){ 
  $scope.interests.splice(arrayIndex, 1);
});

Using $timeout will automatically handle the digest if needed and prevent errors if a digest is already in progress.

Another option is to simply use CSS to hide the li element until Angular has removed it:

.ng-leave { display:none; }

Answer №2

I encountered a similar issue with ng-repeat. When I set the item array length to 0, I found that I had to execute a timeout with a lengthy delay:

$timeout(function(){ 
  perform_some_action
}, 2000);

Even using evalAsync did not resolve the issue:

$scope.$evalAsync(function () {
   perform_some_action
});

An alternative solution is to simply disregard old items:

var elems = angular.element(document.getElementsByClassName('repeated_items'));
_.each(elems, function (item) {
   if (item.$$hashKey) return true;
   perform_some_action
});

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

The Colorful World of CSS Backgrounds

I've been searching for hours trying to track down the source of this strange greenish background color. I've combed through every single file and it's starting to drive me insane. Any ideas where this color could be coming from? I highly d ...

Encountering an unusual hash code when implementing Google Tag Manager in a Next.js project was

I am currently using Next.js and have added Google Tag Manager through a script <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...

What situations call for utilizing $scope directly?

As a beginner in Angular, I have been diving into various tutorials to enhance my knowledge. Interestingly, the free tutorial at CodeSchool, which served as my introduction to Angular, does not mention the use of $scope. It appears that the controllerAs s ...

The scroll function is failing to activate at the desired location

I've been trying to fine-tune a window scroll function I created. Initially, I attempted to use waypoints for this, but unfortunately, I couldn't get it to work as expected. The main issue I'm facing is that the function triggers too early ...

Generate a random number to select a song file in Javascript: (Math.floor(Math.random() * songs) + 1) + '.mp3'

My current JavaScript code selects a random song from the assets/music folder and plays it: audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) + 1)+'.mp3' However, I've noticed that sometimes the same trac ...

Difficulty encountered in closing dialog box upon clicking NavLink in React

Currently, I am developing a React application and have integrated a dialog box using the Material-UI library's Dialog component. Inside this dialog box, there is a navigation menu that I would like to close when a user clicks on one of the navigation ...

Using PHP's for loop to iterate through data and store them into arrays

Attempting to transmit data from JavaScript to a PHP file through an AJAX request, and then store each result in an array using PHP. queryData={"data":{"data_string":{"data":"medicine","default_field":"Content"}}} testArgument=0; $.ajax({ url:"test/q ...

What is the best method for invoking a WCF Rest service with a data contract parameter using AngularJS?

[OperationContract] [FaultContract(typeof(DcCustomFaultMessage))] [WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/GetHistoryData")] List<DcHistoryData> GetHistoryData(DcHisto ...

Designing a popup using Angular, CSS, and Javascript that is capable of escaping the limitations of its parent div

I'm currently working on an Angular project that involves components nested within other components. My goal is to create a popup component that maintains the same size and position, regardless of where it's triggered from. One suggestion I rece ...

Use the inline IF statement to adjust the icon class depending on the Flask variable

Is it feasible to achieve this using the inline if function? Alternatively, I could use JavaScript. While I've come across some similar posts here, the solutions provided were not exactly what I expected or were implemented in PHP. <i class="f ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

Javascript code creates a blur effect on webpage bodies

On my webpage, I have multiple elements, including a "change BG" button. When this button is clicked, I want to hide all other content on the page except for the button using JavaScript. Alternatively, clicking the button could blur out all other elements ...

Trouble with jquery/ajax form submission functionality

I followed a jQuery code for form submission that I found on various tutorial websites, but unfortunately, the ajax functionality doesn't seem to be working. When I try to submit the form, nothing happens at all. I've tried troubleshooting in eve ...

Syntax Error Unearthed: Identifier Surprise Discovered in (Javascript, ASP.NET MVC, CSHTML)

I encountered an error when attempting to remove a dynamically created HTML element by clicking the corresponding remove button. The goal is to invoke the remove method at the end of the script and pass along certain arguments. However, I'm facing iss ...

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Jquery(Ajax) call encountered a problem when attempting to send the object

Struggling to send data to a MongoLab DB using JS and JQueryAjax call. The issue lies in being able to see the OID in the DB but no data is actually populated. Upon checking the code and network settings, it's evident that the payload always remains e ...

Utilizing SVG with an integrated script to automatically adjust to the available space within different browser

I am attempting to develop a self-contained SVG document that automatically adjusts its size and centers itself when loaded in a web browser. It's important to note that this is not referring to embedding an SVG within an HTML document. Below is the ...

Retrieving data from radio buttons using React Hook Form

As I delve into learning React and Next.js, working with form submissions has been a breeze thanks to react-hook-form. However, I've hit a roadblock when it comes to handling radio buttons in my application. Specifically, there's a step where use ...

Unable to detect the click event on Bootstrap accordion

I am currently utilizing Bootstrap to populate a table with data and then attempting to capture an accordion show event. My intention is to extract the div id in order to make an ajax call for more information on the respective item. Unfortunately, I have ...