"Exploring the wonders of AngularJS with JSON arrays containing objects

I am currently working on building an array of objects using AngularJS.

Initially, I start with just one object. When the user clicks on a button, it adds another object to my array.

The button functionality is as follows;

HTML:

<button ng-click="ajoutForme()" type="button" class="btn btn-default">+</button>

Angular:

$scope.ajoutForme = function(){
    $scope.nbrForme++;
}

This part works fine and I can see nbrForme increasing on the page.

However, this button actually adds a row that needs to be filled in my table. So, every time the button is clicked, I want to insert a new row into my table.

I accomplish this by doing the following;

Angular:

$scope.row = [];

$scope.$watch('nbrForme', function() {
 for(i=0;  i<nbrForme; i++){
  $scope.row.push({
    id: i
  });  
 }
});

By watching the nbrForme, a new object is created inside the array row every time the button is pressed.

To visualize the changes, I display the row array on my page like this:

HTML:

row = {{row}}

Before pressing the button, there is only one object with an id of 0; Upon pressing the button, I can see the new object being added to the array, but the id always remains 0.

As a result, the output looks like this:

row = [{"id":0},{"id":0},{"id":0},{"id":0},{"id":0}]

Therefore, I am questioning why the i variable is not being properly incremented.

Answer №1

Here's how you can achieve it:

$scope.shapeCount = 0;
$scope.shapes = [];
$scope.addShape = function(){
    $scope.shapes.push({
        id: $scope.shapeCount++
    });
}

Answer №2

You should give it a shot

$scope.addShape = function(){
    $scope.shapeCount++;
    $scope.shapes.push({
            id: $scope.shapeCount
    }); 
}

Consider this approach

for(i=0;  i<shapeCount; i++){
  $scope.shapes.push({
    id: i
  });  
 }

With this method, you start pushing into shapes from index 0 up to shapeCount. This prevents duplicate objects and the possibility of errors when rendering in the DOM using ng-repeat without track by.

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

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...

What is the best way to assign values from an Array to individual PHP variables?

In my quest to extract records from a MySQL database, I am specifically interested in retrieving all the records associated with the img_path column. While the code below successfully returns results as an array, I actually need them as individual variable ...

What is the best way to insert several JSON entries into a mongoDB database?

I am facing a challenge with handling a large JSON data file structured like this: {"created_at":"Wed Apr 15 16:59:38 +0000 2020","id":1250468838409490432,"id_str":"1250468838409490432"} {"created_at":"Thu Apr 16 16:59:38 +0000 2020","id":125046883840439 ...

Switch between parent elements in Angular JS Templates while preserving children elements

It seems like I'm overlooking a rather basic feature in a templating engine. Consider the following template: <a ng-if="icon.link" href="icon.link"> <i ng-class="['fa',icon.icon_class]"></i> </a> <span ng-if= ...

How to Assign Values to a Variable from a JSON Response in ASP.NET MVC

I am struggling with populating a variable from a JSON result in my code. I can't seem to find the right keyword to use for it. My goal is to populate this specific variable. Custom Js File var opts = [ { key: 1, label: 'High' }, { key: ...

Enable users to input their custom code and run it when the specified conditions are met

Currently, I am developing a Multi-tenant application that requires users to input their own code and run it under specific conditions. I have several ideas in mind, but I am unsure which approach would be most effective. All the proposed methods will ha ...

Issue with importing a file using JQuery causing the click event to not function properly

I have a file named navigation.html located in a directory called IMPORTS <!-- Navigation --> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-ta ...

convert a screenplay to javascript

I have a script that can be used to calculate the distance between 2 coordinates. The code is a combination of PHP and JavaScript. I am interested in moving it into a standalone JavaScript file but not sure how to proceed. Below is the script related to & ...

Issues with rendering of triangles in WebGL

My current project involves creating a webGL application for rendering randomly generated terrains. While the terrain rendering works smoothly, I've encountered an issue with rendering a simple quad to represent water - the triangles of the water are ...

How can I use bash and awk to iterate through an array containing 4 elements and retrieve a size of 1?

My current script utilizes awk to match fields with user input. NB=$# FILE=myfile #RECEIVE INPUT if [ $NB -eq 1 ] then A=`awk -F "\t" -v town="$1" 'tolower($3) ~ tolower(town) {print NR}' $FILE` fi Upon printing the output, I receive: ...

Using AngularJS to Bind Complex Object Data from JSON

Exploring the module and controller below angular.module('contactServices', ['ngResource']). factory('ApiKey', function ($resource) { return $resource('/V1/apikeys', {}, { query: {method: 'GET' ...

Having trouble with enabling HTML5 mode to true on an Angular frontend and Laravel backend

I successfully removed the "#!" from my website URL and everything is working perfectly. The only issue I am facing is that when I try to reload a sub URL other than the home page, it shows a "page not found" error. However, I am able to access the same s ...

Nested views within Angular providing a multitude of perspectives

Currently, I am tackling a project at my workplace with my colleagues, but we are collectively stumped on how to proceed. Consequently, the details may come across as nebulous. Allow me to present a preview of the expected layout: Template The plan is fo ...

Maintain the newly selected background color for the current day in fullcalendar when navigating to the next or previous month

Currently, I am working on a project in React using npm fullcalendar. One of the requirements is to change the color of the current day. After some trial and error, I was able to achieve this by adding the following code: $('.fc-today').attr(&ap ...

Improving Vue.js (Vuex) Getter Functions

Currently, I am in the process of restructuring two getters within vuex. Within my state, there exists a predefined array of objects like so: state: { color: 'All colors', size: 'All sizes', allShoes: [ { ...

Error encountered: TypeError: Unable to access attributes of null object (attempting to read 'useMemo')

In the development of a public component titled rc-component version0.1.14, I built a platform that allows for the sharing of common React pages amongst various projects. However, upon attempting to utilize this component in my project, I encountered the f ...

Getting the data from a cell by clicking on a table row

I'm attempting to retrieve the href value from the cell that has the class editlink. However, my current approach is returning undefined in the alert message. <table id="table_1"> <thead></thead> <tbody> <tr> ...

Using Gulp Filter in Conjunction with Source Maps

My initial query was similar to this one here, but it led me to delve deeper into research and explore a new approach. Essentially, I am attempting to consolidate all my .js and .coffee files within a single gulp.src() object and execute relevant tasks ba ...

Managing various conditions in React is crucial for proper functionality

I am facing an issue with the if statement related to creating conditions based on the number of objects in an array. Specifically, I need the condition to be true if there are 2 objects in the array and false if there is only 1 object. These objects are s ...

Avoid opening the page when attempting to log in with jquery, ajax, and php

I am facing an issue with my code. I have a file named "index.html" which contains a login form. Another file called "dash.js" retrieves the username and password from the login form and redirects to "connectdb.php" to check the login credentials with the ...