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

Integrate a scrollbar seamlessly while maintaining the website's responsiveness

I encountered an issue where I couldn't add a scrollbar while maintaining a responsive page layout. In order to include a scrollbar in my datatables, I found the code snippet: "scrollY": "200px" However, this code sets the table size to 200 pixels r ...

Exploring the power of Angular through the use of promises with multiple

I've come across some forum discussions about angular promises in the past, but I'm having trouble implementing them in my current situation. My backend is nodejs/locomotive and frontend is Angular. In the controller code below, I am trying to a ...

Experience the dynamic bouncing marker feature in Next.js React-Leaflet with the powerful tool Leaflet.SmoothMarkerB

I'm a beginner in front-end development and I'm attempting to create a bouncing marker in React-leaflet using the leaflet.smooth_marker_bouncing plugin version 1.3.0 available at this link. Unfortunately, I couldn't find enough documentation ...

Vue-bootstrap spinbutton form with customizable parameters

I am in need of a custom formatter function for the b-form-spinbutton component that depends on my data. I want to pass an extra argument to the :formatter-fn property in the code snippet below, but it is not working as expected. <b-form-spinbutton :for ...

Encountering NotFoundHttpException with Jquery Ajax in Laravel 4

Hello everyone! I'm diving into the world of ajax and currently experimenting with sending form input to a controller through a route and then displaying it in a div. Unfortunately, I've hit a roadblock as I keep getting a NotFoundHttpException ...

Struggling to incorporate my provider into the configuration

Inside app/providers/weather.js: angular.module('forecast').provider('Weather', function() { var apiKey; this.setApiKey = function(key) { if(key) apiKey = key; }; this.$get = function() { return { ... // Som ...

Tips for retrieving javascript-generated HTML content

Currently, I'm attempting to retrieve article headlines from the NY Times website. Upon inspection, it appears that the HTML is being generated by Javascript since it's only visible when using the 'inspect element' feature in Firefox. ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

Vue appears to be having trouble waiting for the axios Post request

While testing a login request, I encountered an issue where jest did not call the mock: This is my test : const User = '123123' jest.mock('axios', () => ({ get: jest.fn(), post: (_url, _body) => new Promise((resolve, reject ...

Detailed enrollment procedure

I am facing an issue with the code in my HTML that validates input types. The system detects empty fields and prevents proceeding to the next step. How can I disable this validation as some of the fields are not required? For instance, the input type < ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...

What is the best way to set conditions for document side script?

I'm struggling to disable the horizontal scroll when the viewport width is 480px or less. The script that controls the scroll behavior on my website looks like this: <script> $(function () { $("#wrapper").wrapInner("< ...

"The changes made to the list are not being accurately displayed by Angular's ng

I am working on a directive that injects dynamic templates during ng-repeat. While I can successfully add items to the list, they do not appear in the view for some reason. It seems like I am missing a crucial piece to make it work correctly. You can find ...

Challenges arise in compiling JS with webpack due to spread syntax complications within an npm package

In my code, I have a class called AnalyticsService with methods for logging analytics events to Google Analytics and Kentico. When trying to reuse this code in different projects by importing it from an npm package, I encountered a compile error related to ...

"Upon invoking the console log, an empty value is being returned when attempting to access the

Why is console.log returning a blank line when trying to retrieve the value of a text input variable? HTML <label for="subject">Subject</label> <input type="text" id=" ...

Using Selenium to handle asynchronous JavaScript requests

Having recently started working with Selenium and JavaScript callback functions, I've encountered a problem that I can't seem to solve on my own. My issue revolves around needing to retrieve a specific variable using JavaScript. When I manually i ...

Struggling to find a solution to adjust an Angular directive

I am attempting to create a functionality where, upon clicking a button, the user can select one of two images displayed and make the selected image draggable. Currently, my code displays two images with only one being draggable. I am struggling to impleme ...

Using ValidationGroup to trigger JavaScript calls from controls

Is it possible to trigger a JavaScript function from the "onclientclick event" of a button that has a ValidationGroup assigned? <asp:Button ID="btnTest" runat="server" Text="Test" OnClick="btnTest_Click" ValidationGroup="Valid ...

Update HTML page sections dynamically when there is a modification in the database table (specifically, when a new row

On my website, users can participate in betting activities. Whenever a user places a bet, a new entry is added to a mysql table. I am looking for a solution to refresh specific sections of the HTML page (not the entire page) whenever a user makes a bet (u ...

Personalized dropdown appearance

During my work on a select box, I discovered that custom styling is not possible. I attempted to use some plugins but did not find one that met my needs. I am seeking a dropdown menu with options in both black and gray, similar to this template but using ...