Eliminate offspring with ng-include and ng-repeat

Can someone assist me with this code snippet? I have a situation with nested ng-repeats and ng-includes, and I am trying to remove an item from any level of nesting. Here's what I've got...

<div ng-repeat="item in List" ng-include="'item.html'">
</div>

The content of item.html:

<div>
   <h1>{{ item.title }}</h1>
   <div ng-repeat="item in item.List" ng-include="'item.html'"></div>
   <button ng-click="removeItem(item)">Remove me!</button>
</div>

I'm struggling with how to access the parent object's List array to remove an item based on its index. Is there a way to pass the parent object into ng-include along with the item?

Answer №1

Is there a way to pass the parent into ng-include along with the item?

I believe passing the parent to the child could lead to code complexity and make maintenance difficult. It may also impact performance, especially with large amounts of data. Instead of using nested directives with isolate scope, a different approach can be taken to remove a node from a nested tree based on a unique value:

function removeFromTree(parent, childNameToRemove){
      console.log(parent);
           parent.nodes = parent.nodes.filter(function(child){ 
             return child.name !== childNameToRemove;
           }).map(function(child){ 
              return removeFromTree(child, childNameToRemove);
           });
    return parent;
   }


    $scope.removeItem = function(item){
       $scope.displayTree[0] = removeFromTree( $scope.displayTree[0], item.name);
    }

Check out the demo plunker here


Full Code

HTML

<div ng-controller="DialogDemoCtrl">
          <div class="span5 article-tree">
          <div ng-style="{'overflow': 'auto'}">

            <script type="text/ng-template"  id="tree_item_renderer">
              <span>
                 {{showNode(data)}} 
              </span>
             <button ng-click="removeItem(data)">Remove me!</button>
              <li ng-repeat="data in data.nodes" class="parent_li"  ng-include="'tree_item_renderer'" tree-node></li>
              </ul>
            </script>

            <div class="tree well">
          <ul>
            <li ng-repeat="data in displayTree"  ng-include="'tree_item_renderer'"></li>
          </ul>
        </div>
      </div>
    </div>
</div>

JS

angular.module('plunker', ['ui.bootstrap'])
.controller('DialogDemoCtrl', function ($scope, $http) {

     buildEmptyTree();   


    function removeFromTree(parent, childNameToRemove){
      console.log(parent);
           parent.nodes = parent.nodes.filter(function(child){ 
             return child.name !== childNameToRemove;
           }).map(function(child){ 
              return removeFromTree(child, childNameToRemove);
           });
    return parent;
   }


    $scope.removeItem = function(item){
       $scope.displayTree[0] = removeFromTree( $scope.displayTree[0], item.name);
    }        

 function buildEmptyTree() {

        $scope.displayTree =
            [{
            "name": "Root",
            "type_name": "Node",
            "show": true,
            "nodes": [{
                "name": "Loose",
                "group_name": "Node-1",
                "show": true,
                "nodes": [{
                    "name": "Node-1-1",
                    "device_name": "Node-1-1",
                    "show": true,
                    "nodes": []
                }, {
                    "name": "Node-1-2",
                    "device_name": "Node-1-2",
                    "show": true,
                    "nodes": []
                }, {
                    "name": "Node-1-3",
                    "device_name": "Node-1-3",
                    "show": true,
                    "nodes": []
                }]
            }, {
                "name": "God",
                "group_name": "Node-2",
                "show": true,
                "nodes": [{
                    "name": "Vadar",
                    "device_name": "Node-2-1",
                    "show": true,
                    "nodes": []
                }]
            }, {
                "name": "Borg",
                "group_name": "Node-3",
                "show": true,
                "nodes": []
            }, {
                "name": "Fess",
                "group_name": "Node-4",
                "show": true,
                "nodes": []
            }]
        }];
        [{
            "name": "Android",
            "type_name": "Android",
            "icon": "icon-android icon-3",
            "show": true,
            "nodes": []
        }];
    }        
});

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

How to use jQuery to delete the final table in an entire HTML document

This situation is really frustrating: When I make a jQuery Ajax call, the success callback returns an entire HTML page. The returned page looks like this: <html> <head> <title>Title</title> <body> <table></table> ...

Transferring data from jQuery Ajax to PHP

I'm facing a challenge in retrieving a value back to PHP that I can manipulate and save to the database. It appears that using the GET method with jQuery AJAX is not yielding the desired results. Below is the PHP code snippet where I attempt to captur ...

Leveraging jQuery functions with dynamically generated DOM elements in JavaScript

On my website, I have a button that dynamically generates a dropdown menu, a textfield, and two buttons when clicked. The purpose of the textfield is to track the quantity selected, while the two buttons allow users to increase or decrease the value by 1. ...

Having Trouble with Sending Emails Using Google Scripts - Javascript POST Request Issue

I have been working on setting up a basic form on my website where users can input their name, email, and a short message. This information is then sent to Google Apps Script which forwards the message to me via email. Unfortunately, I keep encountering an ...

Retrieving a function's output in React

Upon attempting to retrieve and log the res.data from my function, I encountered an issue where it returned as undefined. However, when I logged it from within the function, the result appeared normal. const getDefaultState = () => { axios .get ...

Guide to integrating the office-ui-fabric-react library into your current MVC project

Our team has embarked on developing an application and we've decided to integrate it with office-ui-fabric-react. While I am familiar with installing packages using npm, I am unsure about where to install both NodeJs & gulp. I have a repository na ...

How to Locate Values of JSON Array Objects by their Key Names

Is there a JavaScript implementation similar to HashMap for sorting JSON data in the following scenario? Here is an example of the JSON structure: { "level1": { "level2": [{ "product1": [ "item1", "item2" ] ...

Missing element causing jQuery function to fail

In order to display error messages on my page, I utilize a tool-tip. It is important for me to close the tool-tip when I click elsewhere on the view. To achieve this functionality, I have implemented the following code: $(':not(.qtip)').click(fu ...

Solving the issue of redirecting with while-else loop in Express.js

app.post('/process', function(request, response){ var i = 0; while(i < data.length){ if(data[i].condition1 == condition1 && data[i].condition2 == condition2){ response.redirect('/first_page'); ...

Reloading data in Angular using jQuery DataTables

After successfully implementing the jQuery datatables library, I encountered an issue where new data retrieved from my API was not displaying inside the datatable as expected. Instead, it was being shown below the table using ng-repeat. It seems that the d ...

Issues with jQuery slide operation

I'm facing an issue with jQuery and I can't figure out where it's coming from. Here is the error message that keeps showing up in the console: Uncaught TypeError: Object [object Object] has no method 'getElement' script_16.js:46Un ...

Using caret range and package-lock.json to acquire the most recent non-disruptive versions

I understand the purpose of package-lock.json, but I'm unsure about how the caret range works after adding this file. Let's say I have a package called my-module and I want to automatically receive all new non-breaking versions without manually ...

What is the best way to bring a list from one .js file into my main.js file?

Here is a demonstration using Ania Kubow's Climate change API. My query is: I have a lengthy list similar to this one, and I would like to store it in a separate file named "exampleList.js" and then import it into my main.js file. const newspapers = ...

Arranging JavaScript object by object properties (name)

Can anyone assist me with my training? I am currently learning JavaScript (Js) and TypeScript (Ts) by working with an external public API. After successfully fetching and displaying my data, I now want to implement sorting functionality. My goal is to sor ...

Error: Module instantiation failed due to an uncaught error

Oops! Encountered an Uncaught Error: [$injector:modulerr] for failing to create the module myApp. The error message reads: Error: [$injector:nomod] Module 'myApp' cannot be found! This could be due to a misspelled module name or forgetting to loa ...

I am looking to extract solely the numerical values

Programming Tools ・ react ・ typescript ・ yarn I am trying to extract only numbers using the match method But I keep encountering an error Error Message: TypeError: Cannot read property 'match' of undefined const age="19 years ...

angularjs issue with displaying content in ui-view element

I am currently following a tutorial on the MEAN stack to gain familiarity with it. I have reached the part where they introduce routing configuration using ui-router. Despite setting everything up as instructed, my page is not rendering anything in the < ...

jquery method for retrieving default value from dropdown list

When no option is selected from the dropdown list, I require the default value to be used for business logic purposes. ...

Django DRF functions properly, however it returns an error when sending a response to an AJAX request

Successfully implemented an AJAX request using PUT in DRF. All functionalities are functioning correctly except for the error callback being triggered: DRF section: class ProductDataViewSet(viewsets.ViewSet): authentication_classes = [SessionAuthentic ...

Disable button with Checkbox Javascript functionality

In my PHP code, I have an array of users that I pass to the view (in Laravel) and use a foreach loop to display all users in a table. Everything is working fine so far. However, I want to make a "send" button visible when a checkbox is clicked, instead of ...