Adding an item to a JSON array in Angular

I'm having trouble adding a new item to the roleList JSON array. I've tried using push/concat, but it doesn't seem to update the roleList array. Any suggestions on how to resolve this?

// The javascript :

function RoleListCtrl($scope)
{
    $('#myTab a[href="#role"]').tab('show');

    $scope.newCompanyName ="";
    $scope.newPosition="";


    $scope.addRole = function()
    {
        var newRole = new function() {
            this.companyName = $scope.newCompanyName;
            this.position    = $scope.newPosition;
            this.id          = '';
        }

        alert("test :"+newRole.companyName);

        $scope.roleList = $scope.roleList.push(newRole);
        // I have also tried this :   $scope.roleList = $scope.roleList.concat(newRole);
    }

    $scope.roleList = [
        {"companyName": "Company 01", "id":"1", "position": "CEO"},
        {"companyName": "Company 02", "id":"2", "position": "Board of Director"},
        {"companyName": "Company 01", "id":"1", "position": "CEO"},
        {"companyName": "Company 02", "id":"2", "position": "Board of Director"}

    ];
}

Here is the button that calls the addRole() function :

<form class="form-horizontal">
<div id="myModal" class="modal hide fade" ng-controller="RoleListCtrl">

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3>Add Role</h3>
    </div>

    <div class="modal-body">

        <div class="control-group">
            <label class="control-label pull-left" for="name">Company Name</label>
            <div class="controls">
                <input type="text" id="coyName" ng-model="newCompanyName" placeholder="Company Name">
            </div>
        </div>

        <div class="control-group">
            <label class="control-label pull-left" for="name">Role</label>
            <div class="controls">
                <input type="text" id="newRole" ng-model="newPosition" placeholder="Role">
            </div>
        </div>

    </div>

    <div class="modal-footer">
        <a href="#" class="btn">Close</a>
        <a href="#" class="btn btn-primary" ng-click="addRole()">Save changes</a>
    </div>

</div>
</form>

<div class="tab-pane" id="role" ng-controller="RoleListCtrl">

                    <a class="btn btn-primary" data-toggle="modal" data-target="#myModal"><i class="icon-plus icon-white"></i>Add New Role</a>
                    <BR>

                    <table class="table table-bordered table-white spacer5">
                        <tr>
                            <th>company name</th>
                            <th>position</th>
                            <th>action</th>
                        </tr>

                        <tr ng-repeat="eachRole in roleList">
                            <td>{{eachRole.companyName}}</td>
                            <td>{{eachRole.position}}</td>
                            <td>
                                <button ng-click="deleteRole($index)">delete</button>
                            </td>
                        </tr>

                    </table>
                    <BR>

                </div>

Answer №1

The issue lies in this particular line:

Make sure to take note of this problematic line of code: $scope.roleList = $scope.roleList.push(newRole);

It's worth mentioning that when you use the push method, it actually returns the length of the array (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push). By executing this line, you are adding the new role to the array, but then inadvertently replacing the entire roleList with just the length value, effectively losing the original array.

Answer №2

let existingRoles = $scope.currentRoles;
let newRoles = existingRoles.concat(addedRoleArray);
$scope.currentRoles = newRoles;

Answer №3

If you want to add a new role, simply create an object with key-value pairs and push it directly into the role list.

$scope.addRole = function(){
var newRole = {
    "companyName":$scope.newCompanyName,
    "id":"",
    "position":$scope.newPosition
 }
$scope.roleList.push(newRole);
}

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

The callback function is not being executed in the Ajax request

$(document).ready(function(){ var requestURL = 'http://www.football-data.org/soccerseasons?callback=?'; $.ajax({ type: 'GET', dataType: 'json', url: requestURL, success: function(data){ cons ...

Incorporate and interpret a custom JSON object within my Shopify Liquid theme

In an attempt to integrate custom data into my Shopify liquid theme, I stored a JSON file in the assets folder. My goal is to retrieve and parse this JSON object within a jQuery method from a JavaScript file also located in the assets folder. Despite try ...

Exploring the Depths: A Guide to Selecting Nodes in Java Based on Depth

In my current JSON representation, I have the following structure: { "total": "555", "offset": "555", "hasMore": "false", "results": [ { "associations": { "workflowIds": [], "companyIds": [], "ownerIds": [], ...

Nginx is responsible for handling files for routes that are not found within the AngularJS application

I have successfully created an AngularJS app (v1) that is packaged as a Docker image with Nginx as the web server. I need the app to display index.html when users navigate to http://localhost:5000/content and login.html when they go to http://localhost:500 ...

Unable to track user (Mineflayer - Node.js)

Trying to track a player using the mineflayer library in Node.js, but encountering an error within the source code of the library itself. Attempted code: const mineflayer = require('mineflayer'); const { pathfinder, Movements, goals } = require( ...

What is the best method to retrieve the single board from JIRA Agile using the JSON REST API?

Looking to access the One Board in JIRA Agile through the JIRA JSON API? Wondering how to do that? Is there a specific location I can search for swim lane details, and another spot for ticket information with data defining their swim lanes? Curious about ...

Is the Site Header displayed depending on the scroll position and direction of scrolling?

On my website, I have a header that I want to hide when the user scrolls down 100px and show again when they scroll up 50px. I attempted to write a script for this functionality, but it doesn't seem to be working as expected. CSS /* This CSS rule w ...

Locate the div in the array that includes ValueA, and save ValueB from it into a new variable

When the button is clicked, I retrieve the current value of a Select control using the following code... $('#myBtn').on('click', function (clickEvent) { var nameSelected = document.getElementById('mySelectControl').getEle ...

Encountered a runtime error in Xcode Swift: Thread 1 terminated due to signal SIGABRT while attempting to display

I need assistance with two issues. 1. I am consistently receiving a signal SIGABRT error and cannot pinpoint the cause. The suggested solutions have not been successful. Project can be found below! 2. After retrieving data from my website, how can I effect ...

Issues with the Diagonal HTML Map functionality

I'm seeking assistance to implement a unique Google Maps Map on my webpage. I have a particular vision in mind - a diagonal map (as pictured below). My initial approach was to create a div, skew it with CSS, place the map inside, and then skew the ma ...

Using Local Storage to store arrays in JavaScript/jQuery

Currently, I am implementing a set of multiple buttons each containing data-id and data-name Below is my concept along with some sample code for reference: $(".clickCompare").click(function ({ var id = $(this).attr('data-id'); var ...

Steps for relocating Express server (using MERN stack) to a subdirectory and functioning on Heroku

In my MERN stack project, I recently had to reorganize the server-related files into their own subdirectory due to issues with ESLINT, VSCODE, and package.json configurations that were causing errors. However, after making this change, Heroku started thro ...

Angular Error: [$compile:ctreq] The specified controller 'abc' for the directive 'def' cannot be located

I have been following a tutorial and consulting the documentation, but I am still unable to figure out what mistake I am making. Every time I try, I always get errors. Here is my code: <!DOCTYPE html> <html ng-app="myApp"> <head ...

Creating an array of objects sorted in alphabetical order

My task involves working with an array of objects that each have a name property: var myList = [{ name: 'Apple' }, { name: 'Nervousness', }, { name: 'Dry' }, { name: 'Assign' }, { name: 'Date' }] ...

Creating an HTML table with colspan and rowspan using ng-repeat from a deeply nested JSON dataset

I'm working on creating a table layout shown in the attached image: Composite Class Routine Check out my progress so far in this Plunker demo: https://plnkr.co/edit/4WiWKDIM2bNfnmRjFo91?p=preview The JSON data I'm using is as follows: $scope. ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

How to break down nested arrays into multiple arrays in Swift 4?

Using JSON parsing in my news API development brought about significant improvements. Here's how the JSON data structure is organized: > { "status": "ok", "source": "associated-press", "sortBy": "top", -"articles": [ -{ "author": "CHRISTINA A. CA ...

What is the most efficient way to load data just once when a user reaches the bottom of the page?

I am encountering an issue with a webpage that dynamically loads HTML from a PHP script which scraps image links from another site when the user scrolls to the bottom of the page. The problem is that the scraping script takes some time to complete, causing ...

Learn how to incorporate a consistent header and footer across multiple pages on a website with Node.js, ExpressJS, and either hbs or ejs templates

Creating a common header (navbar) and footer page to be included in multiple/several pages of a website. I want to create a dynamic website using Node.js and Express.js. The code for the navbar and footer will be placed in a common file named header.html ...

Exploring the bewilderment of retrieving values in a JavaScript

I'm confused about the return value of this code snippet: function foo() var ret = 0; var xhr=send_request( "bla", function() { // perform actions based on AJAX response // set the value of ret based on the response } ); return re ...