How to generate a collection of identical services in AngularJS

One of the features I have is a Service that can be added by a user, either one or multiple services.

There is a button available for users to add a new Service:

<button type="button" class="btn btn-success" ng-click="addService()">
    <span class=" glyphicon glyphicon-plus">
    </span>Add Service
</button>

Upon clicking the Add Service button, Angular will create a new Service in a list of services.

Additionally, there are two text areas where users can input information about the Service:

<label for="usr">Name:</label>
<input type="text" class="form-control" id="name"></br>
<label for="usr">Service:</label>
<input type="text" class="form-control" id="service"></br>

When the Add Service Button is clicked, a new Service Button should be generated with these text areas.

Is there a way to generate this and add the new Service to the list of services?

Answer №1

const myServices = [];
const addMyService = function() {
    const newService = {
        serviceName : 'example name',
        serviceType : 'example type'
    };
    myServices.push(newService);
}

Here is the corresponding HTML structure:

<div ng-repeat="service in myServices"><label for="usr">Name:</label>
<input type="text" class="form-control" value="{service.serviceName}"></br>
<label for="usr">Service Type:</label>
<input type="text" class="form-control" value="{service.serviceType}"></br></div>

Answer №2

To achieve two-way binding of fields to a scope object, you would implement the ng-model directive in AngularJS.

<label for="usr">Name:</label>
<input ng-model="newService.name"></br>
<label for="usr">Service:</label>
<input ng-model="newService.service"></br>

In your controller:

$scope.addService = function() {
     // Copy and push the newService object to an array
    $scope.services.push(angular.copy($scope.newService));
    // Reset newService object to clear fields
    $scope.newService = {};   

}

If utilizing a form, you can leverage Angular validation by moving the ng-click event to ng-submit on the form. This ensures that ng-submit will only trigger if validation passes.

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

Conceal the div element if the screen size drops below a certain threshold

Is it possible to hide a div element when the browser width is less than or equal to 1026px using CSS, like this: @media only screen and (min-width: 1140px) {}? If not, what are some alternative solutions? Additional information: When hiding the div eleme ...

Exploring AngularJS's capabilities with Cross Domain POST requests

One query I have concerning CORS requests that include the HTTP Authorization header: I've noticed that the web browser doesn't seem to send the Authorization header with POST requests, is there a workaround for this? Below is the Angular code ...

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 ...

Encountering problems with binding AngularJS directive controller functions while utilizing ng-repeat

Here is a sample code snippet: JavaScript var app = angular.module('app',[]); app.controller('ctrl',function($scope){ $scope.hello = "hello"; $scope.check = [1,2]; $scope.focus1 = function(){ $scope.setFocusInput0(); ...

What sets apart the concept of asynchrony in C# from that in JavaScript?

When working with Python and JavaScript, a common issue arises due to blocking the event loop. This occurs when code is executed in a single thread and only one synchronous operation can be performed at a time. Interestingly, this problem does not seem t ...

Error encountered in Parse cloud code: Unexpected character sequenceJavascript

I am attempting to retrieve information from an httpresponse, parse the JSON, and create a new dictionary with an array of dictionaries similar to: "data" : {"infracciones": [ { "folio": "03041487403", "fecha": "2014 ...

Using Three.js to create a React button positioned above a canvas

Here's the code I have written using three.js in a React component. I am looking to add a button above the canvas. How can I achieve this? Additionally, I would like to know how to add a click event on objects rendered in three.js. import React, { Com ...

A guide to filtering an Array based on Name using AngularJS

Within my project, I have a table that contains an array which I am looping through. I would like to provide users with the option to filter the table by displaying either their data associated with their name or showing all data. Here is an example of my ...

Is there a way to determine if a file is an audio or video file using Vue.js by examining its URL?

I am currently working on a Vuetify playlist that contains a mix of audio and video media files. My goal is to create functionality that allows me to launch a video player if the file is a video, or utilize the html5 audio component for .mp3 files: ...

I am encountering an issue with CreateJS where I receive the error message: "createjs is not defined"

Looking for assistance with my createJS issue. var stage = new createjs.Stage(canvas); Encountering the following error : angular.js:13642 ReferenceError: createjs is not defined, even though I have EaselJS in my bower-components. Appreciate any hel ...

In situations where there may be a duplicate, what alternative can I utilize in place of the id attribute?

I understand that almost any element in the DOM can have an "id" attribute, and I've used it to track each client in a table of clients. Although ids should not be repeated, my rows are assigned unique identifiers based on each person's "clientId ...

A step-by-step guide on extracting nested ASP.NET DataGrid values with JavaScript

Looking to retrieve data from a nested data grid on an aspx page using JavaScript. Check out the following code snippet: <tr> <td colspan="2" align="center"> <asp:DataGrid ID="sampleData" AutoGenerateColumns="false" runat="serv ...

The Angular filter does not seem to work as expected when combined with the ng-if

There seems to be a problem with filtering an ng-repeat using a search box. <li ng-if="searchTab"><input type="text" class="form-control" placeholder="Search" ng-model="search" > </li> and then in the ng-repeat <div dir-paginate= ...

Collect form input data containing a binary image and showcase it in a view using webapi

I am currently working on a webapi project using MVC architecture. The project involves converting a jpg image to binary data, sending it to a SQL server, and then retrieving the form data along with the image back as a jpg for display on the view. Althoug ...

How to sort multiple columns in AngularJS while keeping records 'Always on Top'?

I am currently working on a table that requires sorting, specifically by two columns (date and 'has attachment'). However, I would like to prioritize certain records (pinned) at the top of the table before sorting the rest of the rows. Html Code ...

Creating a duplicate of the Object in order to include a new key and value pair

While pre-fetching a product from a database using mongoose along with next.js and react-query, I encountered a situation where I had to perform a deep copy of a nested object to successfully add a key-value pair to it. Without this deep copy, the operat ...

Is it possible to use JQuery ScrollTop while in the midst of an animation?

I am facing an issue with resizing containers and scrolling to elements. I have 2 containers that change width dynamically, each containing clickable elements. When a container is clicked, it animates the resize. However, when a clickable element is clicke ...

Launching an Electron Window and Recording the Closing Event

I am currently developing a Desktop Application using Electron. I want to implement a feature where clicking on a button in the main window (index.html) will open a different window. After researching, I discovered the BrowserWindow from the Electron API. ...

Issue with Laravel retrieving POST data from Angular

My Angular controller submits form data, which should be passed to a Laravel Controller and stored in the database. However, when passing the data to Laravel, it ends up being NULL. Form <form> <div class="form-group"> <label f ...

Learn how to utilize the value of an element attribute to toggle the visibility of a div using AngularJS

Looking to dynamically show a specific div based on the value of its attribute. <div ng-show="" data-views="{{viewstate}}" id="Question_ID_{{questionid}}" >aaa</div> Trying to achieve something similar to this: <div ng-show="data-views" ...