An overview on adding a new element to an array of objects in AngularJS

I have a feature on my website where users can create via points. Each user starts with one point, and if they want to add more, they can click "add" to insert a new object in the array with an empty value. The user then has the option to input a new value for the added point. Users can continue adding via points until they reach 5. How can I achieve this? Below is my code snippet.

My requirements are:

  1. Users should be able to create via points by adding a new item with val="" and then change the value using an input field.
  2. Once 5 via points are reached, no more additions should be allowed.

Any assistance would be greatly appreciated!

//HTML

<table>
    <tr ng-repeat="item in viaPoints">
        <td>

            <p class="title-icon form-label">VIA LOCATION {{$index + 1}}</p>

            <button style="bottom: -3px;" class="transparent position pull-right" ng-click="removeViaPoint($index)">
                <img src="images/icons/close-14.png">
            </button>

            <input class="form" id="drop-off" type="text" value="{{x}}" ng-model="item.val">

        </td>
    </tr>
</table>

<button class="add" ng-click="addViaPoint()">+ ADD MORE LOCATIONS</button>
<button class="okay okay-full">OKAY</button>



//Angular


var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

//Via Point Objects


$scope.viaPoints = [

{val:"Hanoi"}

]

//Push Via Points

$scope.addViaPoint = function () {
    $scope.viaPoints.push("val:''");
}

//Remove Via Point

$scope.removeViaPoint = function (x) {
    $scope.viaPoints.splice(x, 1);
}

});

Answer №1

When you use the function $scope.addViaPoint(), be mindful that it will only add a string to the array. To add an object instead, modify the code as follows:

$scope.addViaPoint = function () {
  $scope.viaPoints.push({val:''});
}

This change ensures that a new object with a property val set to '' is added.

To restrict adding more than 5 points, incorporate a validation check in your function. For instance:

if ($scope.viaPoints.length === 5) return;

You can also enhance user experience by dynamically disabling the button based on the number of points added. Update your HTML accordingly:

<button class="add"
        ng-click="addViaPoint()"
        ng-disabled="$scope.viaPoints.length === 5">
  + ADD MORE LOCATIONS
</button>

(Consider implementing a more versatile approach using a function like reachedMaxViaPoints())

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

Determine in Typescript if a value is a string or not

In my code, I have a component: export type InputData = string | number | null; interface InputData { data?: string | number | null; validate: boolean; } const App: React.FC<InputData> = ({ data = '', validate = true, }) => ...

Utilizing Translation (i18n) in AngularJS Controller to Implement Popups

I'm currently working on an AngularJS app and need to implement i18n. Everything is running smoothly except for error handling, specifically with utilizing translations in controller for popups. Here is a snippet of my controller: function showError ...

How come my directive is being updated when there are changes in a different instance of the same directive?

For the purpose of enabling Angular binding to work, I developed a straightforward directive wrapper around the HTML file input. Below is the code for my directive: angular.module('myApp').directive('inputFile', InputFileDirective); f ...

Choosing a class using Jquery through a For loop in Javascript

I have a group of images with a class applied to them. I am attempting to create a for loop that will iterate through the elements of this class. In Python, you can use "for element in thing" and I was curious if there is something similar in JavaScript. A ...

Having trouble getting Django to display images using jQuery? Uncaught Reference Error may be preventing it

Currently, I am experimenting with implementing a jquery example on my django-based website. As I am still in the learning phase, I kindly ask for your patience. This is a snippet of what my code looks like at this point: {% extends "base.html" %} {% loa ...

Having trouble with my React Next app, it's giving me an error stating "window is not defined

Currently, I am developing in Next.js using React components and encountering an issue. I keep receiving a ReferenceError: window is not defined error in react-location-picker. If you need to check out the package, here is the link: react-location-picker ...

Mocking in AngularJS: Utilizing the same service with varied functions for unit testing with Jasmine

Exploring a new service, Service A, with various functionalities: The snippet of application code is as follows: angular.module('app').factory('ServiceA', function() { var ServiceA = { _retryItem: null, retryItem: ...

Pause the event listener temporarily and reattach it after specific actions have been completed

I am currently working on a React app that includes a scrollable div. Here is an example: <main id="main" onScroll={this.handleScroll}> My question is, how can I temporarily remove the onScroll event listener from the main element and then reattach ...

The debate between utilizing CDN or installing a library through NPM

My journey with NPM has just begun, and I am struggling to grasp how the files within node_modules get integrated into my index.html. Scenario 1: CDN Take jQuery, for instance. When using a CDN, it's as simple as adding the CDN link to a <script& ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

Unable to retrieve innerHTML from a jQuery element

My current task involves implementing the Google Maps API. The code snippet below is what I have written so far: <div id="map"></div> To inspect the content of $("div#map"), I am utilizing the Google Chrome console. console.log($("div#map")) ...

Unintentional GET request triggered by Axios baseURL

I have encountered a strange issue where defining axios.defaults.baseURL = baseUrl; results in an unexpected GET request right after initializing my Vue app. Any assistance would be greatly appreciated! Below are images showing the code and network reques ...

Steps to show a Google Maps marker with the help of ajax

I'm trying to show a "marker" on the map using ajax, but I haven't been able to find a solution despite searching various sources online. ================= Here's the code I currently have: var map; function initialize(){ var center = ...

Is there a way to use Axios to send several HTTP requests to a URL simultaneously, but pause once a response is received from any one of the requests?

As a beginner in javascript, I am working on writing a script that will use Axios to send multiple HTTP requests to a web server. The server randomly responds to the requests, and I want the script to stop sending requests once it receives a response. This ...

Is there a more efficient method for implementing server side rendering in a Next.js application?

Currently, I am implementing server-side rendering in my Next.js application. This specific component is responsible for returning HTML content. I'm wondering if there are more efficient methods available? import Feature from 'components/home/Fea ...

Inject a jQuery form submission using .html() into a div element

I am currently working on developing a basic forum where users can view listed topics and have the option to add new ones on-the-fly by clicking a link or image. How can I detect and handle the form submission event for the dynamically added form within an ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Exploring the differences between Yeoman bower installation, npm installation, and grunt

This is my first time working on an AngularJS project and utilizing the Yeoman scaffolding tool (). I'm interested in incorporating fontawesome icons into my app () and I understand that I should use the following command: bower install fontawesome ...

Having trouble resolving a setInterval problem with JavaScript?

Yesterday, I learned about the setInterval function which allows me to execute a task or function after a specific amount of time. While I have successfully implemented the interval in my code, it keeps adding new lines with the date each time. What I re ...

What is the quickest method to perform a comprehensive comparison of arrays and combine distinct objects?

I am currently working with NextJS and Zustand and I have a state in Zustand that consists of an array of objects: [{a:1, b:2}, {a:2, b:3}] Additionally, there is another incoming array of objects that contains some of the existing objects as well as new ...