Angular.js hierarchical model issue: grandchildren functionality not functioning as expected

Currently, I am delving into the world of Angular and exploring its functionalities. My main goal is to construct a hierarchical data structure that can be easily manipulated using a hierarchical view:

Root:
  - addChild
  - child 1: { remove, addChild, child1, child2, ...}
  - child 2: { remove, addChild, child1, child2, ...}
  ....

(actual code available at http://jsfiddle.net/xtofl/n3jqM/12)

Presently, my aim is to create a structure with 2 levels only, where the Root has children and grandchildren.

When clicking on the 'remove' button for grandchildren, it triggers the child.remove(grandchild) function. However, the removal does not result in the corresponding rows being removed :(

I'm struggling to comprehend the reason behind this issue. Additionally, in the provided fiddle example, it seems to add 4 grandchildren simultaneously.

The key parts of the code are as follows:

function Controller($scope) {
    $scope.nextChildIndex = 1;
    $scope.addChild = function () {
        $scope.children.push(makeChild($scope.nextChildIndex++));
    };
    $scope.removeChild = function (child) {
        $scope.children.remove(child);
    };
    $scope.children = [];
}

var makeChild = function (i) {
    var nextIndex = 1;
    var ret = {
        index: i,
        children: []
    };
    ret.addChild = function () {
        ret.children = makeChild(nextIndex++);
    };
    ret.removeChild = function (child) {
        ret.children.remove(child);
    };
    return ret;
};

The relevant html snippet:

    <ul ng-repeat="grandchild in child.children">
        <li class="grandchild">
            <button ng-click="child.removeChild(grandchild)">-grandchild</button>
            <span>child {{grandchild.index}}</span>
        </li>
    </ul>

Question: What could be causing the unexpected behavior with the makeChild function that results in multiple li elements being added when ng-click="addChild()" is triggered? Moreover, why does

ng-click="child.removeChild(grandchild)"
fail to remove the grandchildren?

Answer №1

your issue does not lie in AngularJS

there was an error with Array.prototype.remove

the correct code is

Array.prototype.remove = function (element) {
    var index = this.indexOf(element);
    this.splice(index,1 );
};

updated link - http://jsfiddle.net/STEVER/n3jqM/13/

UPDATE:

instead of

    ret.children = makeChild(nextIndex++);

you should use

    ret.children.push(makeChild(nextIndex++));

http://jsfiddle.net/STEVER/n3jqM/14/

have fun ;)

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

Enhance Your User Experience with the Onsen UI Bluetooth Extension

Trying to integrate a Bluetooth plugin using Onsenui in Monaca IDE, but consistently encountering the error message: "bluetoothSerial not found." Looking to develop a service that necessitates the Bluetooth Serial plugin. Planning to simply utilize a .is ...

Using infoWindows with multiple markers in Google Maps

i have developed a custom Google Maps application that pulls data from a CSV file. The functionality works well, but I am facing an issue with the infoWindow when looping through all the objects. It seems like the problem stems from the marker variable bei ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

Customize HTML styles using Angular Material

I've noticed that my index.html file has a lot of style elements when using Angular Material, and I'm not sure why. Here's an example in the header element where different classes are used for Angular Material components. https://i.sstatic. ...

Multiple uses of p-fileUpload in primeng are not functioning as expected

Let me explain the situation with this component. I have defined it as follows: <p-fileUpload #fileUpload accept=".csv,.txt" maxFileSize="1000000" customUpload="true" (uploadHandler)="uploadFile($event)"> In my package Json file, I have specified: ...

Creating audio streams using react-player

I am currently working on integrating the react-player component from CookPete into my website. However, I am facing a challenge in setting up multiple audio streams. Additionally, I want to include both DASH and HLS video streams but adding them as an arr ...

Is it possible to pass makeStyles as a prop in React components?

Within my component, I am using a prop named styling to apply inline styles. However, I would like to pass some predefined styles that I have written using the makeStyles function. The specific style I want to pass is detailed below: const useStyles = ma ...

Tips for choosing multiple checkboxes with the input type of "checkbox"

image of my columns and checkboxes <table class="table table-striped grid-table"> <tr> <th>Id</th> <th>Code</th> <th> <input type="checkbox" id="box&q ...

The onmessage event in the websocket client seems to be malfunctioning and is not triggering

In my implementation using node.js, I have set up a websocket server and client. The handshake process between the server and client appears as follows: Request URL: ws://localhost:8015/ Request Method: GET Status Code: 101 Switching Protocols Request ...

Having difficulty implementing a personalized color scheme for the mui component

Attempting to set the background color as midnightBlue but encountering an error: Error: Cannot read properties of undefined (reading '100') Upon reviewing the syntax, no errors were found. Perhaps this issue stems from a dependency problem? ...

What causes jquery-ui resizable to set the width of the div with the "alsoResize" property?

I have created a series of divs structured like this: <div id="body_container"> <div id="top_body"> </div> <div id="bottom_body"> </div> </div> Additionally, I have implemented the following funct ...

Guide on how to load a document and transfer information to a webpage using a single GET request

I am currently utilizing AngularJS on the client-side and Express.js on the server-side. My goal is to render a page and transmit data to populate a table in a single get request. I attempted using the EJS engine to populate the table on the server-side b ...

Discover the process of incorporating secondary links into your dabeng organizational chart!

I need to incorporate dotted lines on this chart, such as connecting leaf level nodes with middle level nodes. import OrgChart from '../js/orgchart.min.js'; document.addEventListener('DOMContentLoaded', function () { Mock.mock(&apo ...

Looking for a way to trigger a function on JSTree's refresh event

I have searched through many posts here but cannot find what I am looking for. The version of JSTree that I am using is 3.3.3. My goal is to select a node after a create_node event triggers an AJAX request. Subsequently, JSTree fires the rename_node eve ...

Using the match.params.id in React: A step-by-step guide

Having some trouble with my React code. I need to display the product name based on its ID, where the product data is fetched from product.js. I am using a router to switch between different products without reloading the page. import product from './ ...

What is the best way to mention @here with an attachment?

I'm attempting to use the canvas say command to display an image with an @here mention included, but unfortunately it only shows the image without making the mention. Below is what I have attempted: message.channel.send(`@here\n`+attachment); ...

Best practices for displaying a Multidimensional JSON Object using JavaScript

Within my current project, I have a JSON object structured as follows: { "face": [ { "attribute": { "age": { "range": 5, "value": 35 }, "gender": { "confidence ...

Ways to dynamically assign a name to a div using AngularJS

Currently, I am in the process of developing a download function for an Android app using Angularjs based on this tutorial: Utilizing the Progress event in PhoneGap file transfers Everything seems to be working efficiently as planned; I can successfully d ...

Which should I use - Angular directive or CSS selector, for better performance?

Currently expanding my knowledge on angular and exploring the capabilities of the ngClass directive. I have come across this interesting functionality: <li ng-repeat="language in languages" ng-class="{line:$even}">{{language}}</li> Alternativ ...

Tick the checkbox to indicate that I want to insert an image in the adjacent column for the same row

Every time I click on the checkbox, an image should appear in the adjacent column for that specific row. Despite using the addClass() method and targeting the td, the image is appearing in all rows instead of just the selected one. Could somebody help me ...