When elements are removed, ng-repeat comments are left in their wake

I have created an inventory system that displays items and allows users to click on certain items to view similar ones. However, I am facing an issue where removing the elements of similar items leaves behind some code snippets...

<!-- ngRepeat: item in category.items(3606) | orderBy:'sort_order' -->
<!-- end ngRepeat: item in category.items(3606) | orderBy:'sort_order' -->

This creates problems because whenever these items are updated elsewhere in the scope, AngularJS recreates the ng-repeat and shows it again. Am I not destroying the element correctly?

app.directive('similar', function($rootScope, $compile, $templateCache, Item, Allo){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {

            var unqId = _.uniqueId('similar');

            elem.on('click', function(){

                // If the user closes the list of similar items, destroy the contents
                if (elem.hasClass('glyphicon-upload')) {
                    elem.removeClass('glyphicon-upload');
                    angular.element('.'+ unqId).remove();
                    return;
                }

                elem.addClass('glyphicon-upload');

                var itemId = scope.$parent.item.id;
                var similars = scope.similars[itemId];

                if (similars) {

                    var row = $templateCache.get('inventory/views/_row.htm');

                    var html = $compile('<tr class="'+ unqId +'" ng-repeat="item in category.items('+ similars +') | orderBy:\'sort_order\'">'+ row +'</tr>')(scope);

                    elem.parents('tr').after(html);
                }
            });
        }
    };
});

Answer №1

Initially, performing DOM manipulation in a directive is often unnecessary. It's possible to achieve your desired result using something like this:

<table similar ng-hide="similar_items.length == 0">
  <tr ng-repeat="item in similar_items" ...>
   <!-- contents of inventory/views/_row.htm here -->      
  </tr>
</table>

The table will stay hidden and the list of <tr>s will be empty if similar_items is also empty. You just need to update that in your scope:

elem.on('click', function() {
   ...
   var itemId = scope.$parent.item.id;
   var similars = scope.similars[itemId];   
   scope.similar_items = category.items(similars);
});

There's no need to manually manipulate the DOM at all - Angular will bind to the similar_items attribute in the scope and handle the <tr> appropriately. Adding or removing the glyphicon-upload class can also be done through similar methods, though the purpose of a class on a hidden element is up for debate :)

This could potentially resolve the issue with leftover comments. I've encountered a similar problem in other situations (modifying the model in the scope after an animation finishes) but have not yet found a solution.

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

Validating Email Addresses Using JavaScript Regex

As a beginner to regex, I am just trying to validate if ([email protected]) works correctly. This is what I have attempted so far. var checkEmail = /^\w+@\w+\.[a-zA-Z]/; Is the above regex pattern suitable for my validation needs? ...

Information will not be displayed when using getjson (undefined)

The data from the API is showing as undefined and I'm not sure why. Here is the HTML snippet: $(document).ready(function() { $.getJSON("https://data.iledefrance.fr/api/records/1.0/search/?dataset=repertoire-bibliotheques&q=&refine.typeins ...

Tips for verifying a list of objects within a request body with JOI

I'm in the process of validating the request body for an order placement. The request body contains an array of JSON objects that I need to validate, but I keep encountering the error message "productId" is required. Below is the structure of my requ ...

Tips on retrieving specific information from PHP through jQuery AJAX

I have encountered an issue with my JavaScript file where I am sending an array of data to my PHP file. The problem is, when trying to print the name in #NAME and password in #PASSWORD, both values end up in both fields. You can see how it currently displa ...

Insert notes into the div employing only vanilla JavaScript

Is there a way to dynamically add comments to a div element using JavaScript or jQuery without reloading the page? Here is an example scenario: Suppose I have a form: <form action="#" id="create" method="post"> <fieldset> <legend ...

Develop a payment confirmation session using Stripe and Node.js

I have set up a POST request using Stripe to handle customer payments let paymentData = { errorMsg:'', key: process.env.STRIPE_PUBLIC_KEY } const session = await stripe.checkout.sessions.create({ payment_method_types: ...

Ways to verify if an item is enabled

To ensure a button in my angular application is enabled, I am using Protractor for testing. Here is the test script: it('submit should not be enabled',function() { var price = by.name('price'), oldCategory = by.name ...

Alter the color of text when hovering over the caption with a mouse

I'm currently working on a layout for a page that features multiple titles in a row, each accompanied by a descriptive paragraph below. My goal is to have the paragraphs dynamically change based on which title the user hovers over. Additionally, I wan ...

When an element is dragged and dropped into a div, an identifier name will be added to the URL

Hey there! I'm new to this and need some guidance. I want to create a feature where users can drag items from a list and drop them into a container div. Once dropped, the item's ID would be added to the URL so that users can share their selection ...

Troubleshooting a cross-origin resource sharing problem in Express.js

I've set up Express as the backend for my client application, but I keep encountering an issue when trying to make a request to the GET /urls endpoint. The error message I receive is: Access to fetch at 'http://localhost:5000/urls' from orig ...

Exploring the functionality of trading-vue library in a simple setup using vanilla HTML and Vue CDN

<html> <head> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a0c0f1f3a48544c544b48">[email protected]</a>/dist/vue.js"></script> ...

updateStatusCallback function is not defined in the Facebook example using jQuery

I've been trying to incorporate Facebook integration into my HTML code, specifically adding features like Facebook login and sharing functionalities. However, I've hit a roadblock in the process. Even after searching extensively for solutions, I ...

New to React and looking for guidance on implementing .forEach or .includes in my code

My task involves going through an array and checking if a string that the user inputs into the form exists in it. This can be achieved using forEach or .includes method. I am basically trying to filter out the array based on the input. If someone could de ...

Tips for generating dynamic scope variables in AngularJS?

I would like to create a screen with select dropdowns and input fields that do not affect each other. Currently, if I select a company, it shows as selected in the next set, which should not happen. How can I implement this? 'use strict'; ang ...

Error: Attempting to access the 'street' property of an undefined value

My application loads a JSONPlaceholder data list of users, and I am attempting to enable editing of this data. However, I encounter an error: TypeError: Cannot read property 'street' of undefined Is there anyone who can provide assistance? c ...

Empty values are being mistakenly assigned to cookies in a production environment within Next.js

My struggle lies in setting cookies with the cookies function within Next.js. While everything works smoothly on localhost, the production environment seems to render empty cookie values. The peculiar thing is that these cookies are being set by the Next.j ...

i am trying to execute a function in an angularjs controller through html, but the scope variable that i am

Being new to angularjs, I'm looking to understand the process of calling a function defined in a controller from HTML within angularjs. I have written the following code in my HTML: First.html <input type="text" ng-model="model.name" name="name ...

Navigating JSON data to retrieve a specific property in AngularJS using a select form

Struggling with AngularJS and JSON. I have a form.html view where users can select their province. I have a Province JSON file for the select tag, but when storing in MySQL, I need the province Id. I tried using ng-value="province.id" in the option tag but ...

What is the best way to extract formatted data from objects using a function?

Below is an example of an object structure: const appUrls = { 'subject': 'Math', 'questions': { 'primary': 12, 'secondary': 13 } 'marks': '100', 'students': ...

Is it possible to utilize AngularJS translate alongside Angular UI Router?

Just starting with Angularjs and keen to integrate angular-translate into my project Check out the site below After referring to its documentation, I encountered an error Uncaught TypeError: Cannot call method 'useStaticFilesLoader' of undef ...