Creating dynamic emails using ng-repeat data binding

I'm struggling to bind the newly added emails to $scope.emails as it does not contain the new email user added. Any suggestions on how to solve this issue?

// On the server side, emails is a List and email is a string

Initially, I tried binding with ng-model="email" but

However, the following code did not work:

$scope.contactInformation.Emails.push(email); --> throws an error about duplicates


<div ng-repeat="email in emails">
    <div class="form-group">
    <label for="email">Email</label>
    <div class="input-group input-group-sm input-group-minimal">
         <span class="input-group-addon">
               <i class="linecons-mail"></i>
         </span>
         <input type="text" class="form-control" ng-model="email" />
     </div>
     <button class="btn btn-primary" ng-show="$last" ng-click="AddEmail()">Add Email</button>

Controller.js

// When retrieved on the server side, modelParams.ContactInformation.Emails is initialized as new List(string)()

$scope.emails = modelParams.ContactInformation.Emails;

$scope.AddEmail = function () {
    $scope.contactInformation.Emails.push({ email: null });
};

Answer №1

To prevent any confusion, I am revising the answer to provide clarity on how it should be implemented - simply fill in the necessary information to tailor it to your specific situation.

controller.js

// assuming 'emails' is an array of strings (whether defined locally or fetched from a server)
$scope.emails = ["email1", "email2", ...];

$scope.addEmail = function(){
  $scope.emails.push(""); // add an empty string as a new email
}

The structure of the HTML code is mostly correct. However, I recommend moving the "add" button outside of the ng-repeat div instead of relying on $last:

<div ng-repeat="email in emails track by $index">
  <input type="text" ng-model="email" />
</div>
<button ng-click="addEmail()">Add Email</button>

EDIT:

The initial example provided would not work as expected because the ng-model within the ng-repeat binds to a primitive (string) value of email. This can be resolved in two ways:

Approach 1

Create an array of objects. If you receive an array of strings from the server, convert it to an array of objects like this:

$scope.emails = [];
angular.forEach(arrayOfEmailStrings, function(value, key){ 
  $scope.emails.push({value: value});
});

Then access it using:

<input type="text" ng-model="email.value" />

Approach 2

Utilize the $index property:

<input type="text" ng-model="emails[$index]" />

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

Swap the content of one div with another div using client-side code only

Currently, I am in the process of developing my personal website. To enhance user experience, I have implemented a vertical navigation bar on the left side of the page. My goal is to replace the content of a specific div with content from other HTML files ...

Sorting rows by words and numbers in JavaScript explained

Hello, I'm a beginner and I need help sorting the table rows in the following table. I also want to attach an onclick listener to the header after it is displayed. ID Name Inventory Volume 1 Rachel Data is not enough 2 Ross 100 3 Monica 1 ...

The timer will automatically refresh when the page is refreshed

Currently, I am encountering an issue while working on a quiz application in PHP. The problem arises when users start the test and the timer is running correctly. However, when users move to the second question, the timer resets again. Below is the code sn ...

How can I ensure that my rendering only occurs after a full input has been entered? Implementing a delayed render() in ReactJS

Im working on a form that includes Controlled Component text inputs: <input type="text" onChange={(e) => this.props.changeBusiness(e)}/> I'm thinking of rendering the above text input in a separate component. It would be great if I could re ...

Assigning a unique identifier to each table row when iterating through a collection using

I have successfully implemented code for generating a table dynamically with angularjs: <div class="col-lg-10 col-sm-10 col-xs-10"> <table class="table table-hover"> <thead> <tr> <th>item</th> <th> ...

Maintaining the selected radio button based on previous input with the use of jQuery or PHP

I am in the process of developing an online quiz system. I am fetching questions and options from getquestion.php through ajax on quiz.html. On this page, I've included next and previous buttons so that users can navigate through the quiz. However, I& ...

Exploring ways to programmatically include questions in the meta.js file of a Vue Webpack template

I have made a customized version of the Vue Webpack template and am currently modifying the meta.js file. I am attempting to figure out how to include a new property in prompts as shown below: "pages": { "type": "input", "required": true, ...

"Mastering the art of utilizing Async in combination with waterfall and Recursion in node

I've developed a script for transferring data from Dynamo to a MySQL database. Initially, I encountered performance issues on the SQL side due to not using asynchronous calls. To address this, I integrated the async library to throttle the Dynamo segm ...

Running karma tests in an angularjs environment may require additional http requests from the configuration

Currently, I am in the process of setting up a Karma test suite using the mean stack as my code baseline. Specifically, I am focusing on writing tests for the login functionality. Here is what it looks like: (function() { describe('LoginController& ...

Analyzing elements within an array of objects

Here is an array of objects I have: const cart = [ { group: "group 1", qtd: 12, value: 65, term: 20 }, //index 0 { group: "group 1", qtd: 10, value: 100, term: 20 }, //index 1 { group: "group 1", qtd: 18, value: 40, term ...

Effortlessly transforming a massive JSON into an Array using ReactJS

I have a large JSON dataset containing information on over 2000 cities. I want to use this data in my React app, but first I need to convert it into an array. A similar question has been asked before, but I couldn't find any answers that fit my specif ...

Assembling back-end interfaces

While working with AngularJS's $http service, I've faced challenges in organizing all the backend URLs throughout my controller code. Sometimes they end up being duplicated and scattered around which can make maintenance difficult. Typically, the ...

Tips for styling a React JS component class

I am attempting to write inline CSS for a React JS component called Login, but I keep encountering an error. What could be causing this issue? Could you provide guidance on the correct way to implement in-line component CSS? import React, {Component} from ...

An interactive chatbox powered by AngularJS, WebAPI, and SignalR, similar to the

Can anyone recommend a live chat box solution for my application that is specifically designed for customer use? It should also have the capability to provide auto replies for certain pre-defined questions. I am currently utilizing angularjs and asp.net ...

Extracting data from website's table using JavaScript and opening the link in href

My goal is to extract the details page for each link found on this particular page. The link provides access to all the information required: PAGE However, I'm interested in extracting details from pages that have links like this: href="javascr ...

Start the setInterval function again after clearing it with the clearInterval button, but wait for

Currently, I am working on a content slider that automatically cycles through slides using the "next" function and setInterval. However, I want it to stop when the user clicks on the prev/next buttons by using clearInterval. Is there a way to resume setInt ...

Tips for sending dynamic column and row information to antd table

https://i.sstatic.net/XY9Zt.png The following code does not seem to work for an array containing rows and columns Below is an example using antd: const data = []; for (let i = 0; i < 4; i++) { data.push({ key: i, name: `Edward King ${i}`, ...

Load images easily using jQuery

I am experiencing a small problem. I am attempting to display an image, but it doesn't seem to be correct. Although I am able to retrieve the data of the image, my goal is just to display it instead. What could be causing this issue? var imageUrl = ...

What could be causing the misalignment between the desired output and the response from the AJAX request

Below is a basic JavaScript file I am working with: $.ajax({ url: "is_complete.php", type: "post", success: function (data) { if(data == 1) { } alert("ok") } }) The message "ok" will only be di ...

Whenever I click on <a href="whatever.aspx"></a>, I would like the page to be displayed within the current page

This is the code I am working with: <asp:DataList ID="dlGallery" runat="server" RepeatLayout="Flow" Width="100%" CellPadding="4" ForeColor="#333333"> <AlternatingItemStyle BackColor="White" ForeColor="#284775" /> <FooterStyle BackColor ...