Removing an object from a JSON data structure using AngularJS

Currently facing a minor issue here. I have a nested JSON object that is embedded within ng-repeat and is sortable by using AngularJS UI Sortable (based on JQuery UI Sortable):

$scope.rootItem = {
        id: '1',
        type: 'course',
        title: 'Adobe Photoshop CC for beginners',
        items: [{
            id: '2',
            type: 'label',
            title:'label',
            items:[{
                id: '3',
                type: 'module',
                title:'Module title',
                items: [{
                    id: '4',
                    type: 'topic',
                    title:'Topic title',
                    items: [{
                        id: '5',
                        type: 'content',
                        title:'Content title'
                    }, {
                        id: '6',
                        type: 'content',
                        title:'Content title'
                    }]
                }]
            },{
                id: '7',
                type: 'resources',
                title:'Resources'
            },{
                id: '8',
                type: 'module',
                title:'Module title',
                items: [{
                    id: '9',
                    type: 'topic',
                    title:'Topic',
                    items: [{
                        id: '10',
                        type: 'question',
                        title:'Question title'
                    }]
                }, {
                    id: '11',
                    type: 'topic',
                    title:'Topic title',
                    items: [{
                        id: '12',
                        type: 'content',
                        title:'Content title'
                    }]
                }]
            }]
        },{
            id: '14',
            type: 'assessmentLabel',
            title: 'Assessment Label',
            items: [{
                id: '15',
                type: 'assessment',
                title: 'Assessment Title',
                items: [{
                    id: '16',
                    type: 'courseAssessment',
                    title: 'Course Question Group',
                    items: []
                }]
            }]
        }]
    };

The task at hand is to remove any item within this object along with its children if it has any.

My initial thought was passing either $index and using splice to remove it (if it was an array). However, for objects, this approach doesn't seem to work as expected. I came across recommendations online suggesting the use of delete instead...

In my button setup, I attempt to pass the object itself as shown below:

data-ng-click="removeItem(ngModelItem)"

Then in my controller, trying to achieve something like this:

// Remove Item from the list
    $scope.removeItem = function(item) {

    };

Looking for suggestions on how to correctly handle this situation.

Answer №1

Utilize the ngModelItem directive.

<li ng-repeat="innerItem in ngModelItem.items">
    <a href="#" ng-click="deleteItem(ngModelItem.items, $index)">Remove</a>

within your controller,

$scope.deleteItem = function(collection, index){
    collection.splice(index,1);
};

See Demo

Answer №2

To delete specific JSON elements from a JSON object, the recommended approach is to utilize the delete operator. However, if your goal is to remove a JSON object from a JSON array, it is advisable to leverage the splice() method instead.

In your removeItem() function, ensure that you receive both the list and the index as parameters. This way, you can successfully remove the specified element, allowing AngularJS to update the view accordingly.

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

Execute an npm script using a gulp task

Is there a way to execute an npm script command within a gulp task? package.json "scripts": { "tsc": "tsc -w" } gulpfile.js gulp.task('compile:app', function(){ return gulp.src('src/**/*.ts') .pipe(/*execute npm run tsc*/ ...

Troubleshooting localhost issue with a Chrome extension in Visual Studio Code

When working in VS Code, I encountered an issue with launching my HTML AngularJS project on localhost. Every time I try to launch the project, I receive an error message stating "Failed to load resource: net::ERR_CONNECTION_REFUSED (http://localhost:8080/) ...

Can you locate the hiding spot of the express-session cookie?

After setting a very short cookie max-age (10 secs) in my express-session, I confirmed that it is working as expected: app.use(session({ secret: 'xxx', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: 10000 } })); ...

What is the best way to retrieve the Json data in React Native as indicated in the following example?

The data in JSON format follows a specific pattern. This JSON data is received from the backend through an API call and stored in a state variable. { "message": "user created successfully", "status": "success", "student": { "class": "1 ...

Using regular expressions, you can conveniently extract text that is contained within paragraph tags

I attempted to use RegExp in JavaScript to extract text between paragraph tags, but unfortunately it isn't working... Here is my pattern: <p>(.*?)</p> The text I am trying to extract from is: <p> My content. </p> <img sr ...

Encoding and Decoding Wot Json API

Here is some Json data I retrieved from : { "google.com": { "target": "google.com", "0": [94, 73], "1": [94, 73], "2": [94, 73], "4": [93, 67], "categories": { "501": 99, "301": 4 ...

When trying to view the page source in Next.js, the page contents do not display

I made the decision to switch my project from CRA to nextjs primarily for SEO purposes. With Server Side Rendering, the client receives a complete HTML page as a response. However, when I check the source of my landing page, all I see is <div id="__next ...

Understanding the request URL in Ajax when receiving a response

How can the URL of a jQuery request be retrieved from the response received? Perhaps something like this: function retrieveUrlFromResponse(response, url){ requestUrl = url; } ...

JavaScript's Date() function accurately displays the timezone, but it inconsistently displays the

I have encountered an unusual behavior while attempting to retrieve the current date using Date() in JavaScript. Initially, I changed the timezone to Cuba with the command: sudo ln -sf /usr/share/zoneinfo/Cuba /etc/localtime Subsequently, I executed Date ...

Views for registering with Ionic

I am in the process of developing a registration view, but I am encountering an issue with the checking statement to determine if the user is already registered. This check currently occurs within $ionicPlatform.ready as shown below: $ionicPlatform.ready( ...

What are the steps for implementing JSON in C++ with a custom object?

I'm considering utilizing JSON in C++ from https://github.com/nlohmann/json#examples. Even after reviewing the basic examples, I'm still unsure how to implement it with my own object. For instance, I have a class: class Student { public: Stu ...

A Complication Arises with Browser Functionality When Embedding an Iframe within

I am experiencing a peculiar problem while embedding an iframe with a specific src inside an absolutely positioned div. Here's the basic structure of the webpage: .container { position: relative; overflow: hidden; width: 100%; heigh ...

Unable to display scrollbar when generating dynamic content with jquery ajax

I have a jQuery report where I am generating dynamic HTML content (nested divs, span, label) using JSON. The report utilizes jQuery, mCustomScrollbar, commons, and jQueryUI. When I have a <div>...//some static code </div>, everything works per ...

Encoding MySQL query in JSON

I am working on a script that executes a MySQL query, and if there are rows returned, it encodes a message. However, I would like the message to include not only its own content but also the entire result of the query. Here is the code snippet I am current ...

Leverage AngularJS to effectively parse JSON data using scope variables

I am trying to JSON parsing in AngularJS using $stateParams in the controller below: rerunApp.controller('rerunCategoryListCtrl', function($scope, $http, $stateParams) { var stpNameCat = $stateParams.nameCat; $http.get(JSON UR ...

Save information for each session with a set expiration time

Currently, I am working on a mobile application using Angular (specifically Ionic 5) and I am in need of a solution to maintain session data for my users throughout their workflow. Initially, I thought about utilizing the sessionStorage feature for this p ...

What is the rationale behind TypeScript's decision to permit omission of "this" in a method?

The TypeScript code below compiles without errors: class Something { name: string; constructor() { name = "test"; } } Although this code compiles successfully, it mistakenly assumes that the `name` variable exists. However, when co ...

What is the best method for inserting a line break into a string?

Can you please explain how I can insert a line break into a string with JavaScript? I have tried using the <br/> tag, but it's not working. What is the correct way to achieve this? JavaScript var str="Click Here" +"<br>"+ "To Set" +"< ...

Utilize Json parsing to extract and display precise data

This is a snippet of JSON code and I am attempting to execute it: Sub test() Dim req As New MSXML2.XMLHTTP60 Dim URL As String, ws As Worksheet Dim json As Object, r, r1 As String URL = "https://www.nseindia.com/api/quote-equity?symbol=DIVISLAB" ...

Retrieve the footer of a RadGrid nested within a NestedViewTemplate for a child

I am working with a RadGrid that has expandable rows, each of which contains a RadGrid within a NestedViewTemplate. These child RadGrids have visible footers and a few columns, one of which is "DtlTransAmount": <NestedViewTemplate> <asp:Panel ...