Associating user input information with an AngularJS object

Currently, I am working on a project that involves inputting a user's ID, first name, and last name. Once the input is received, a user object is created and stored inside the logins array.

My goal is to display each new user as the next item in an unordered list every time the login button is clicked. However, I am encountering issues when trying to clear the text boxes after the first entry. How can I accurately bind my input to the user object while ensuring that each new user is displayed? Essentially, I want to add multiple users and have them all appear in the list. While they are being added to the array correctly, the display seems to be where the problem lies.

I suspect that my approach to capturing the data input from the text boxes may be causing the variables to be set only upon entry. As someone who is relatively new to Angular, any assistance would be greatly appreciated.

Code:

<!DOCTYPE html>
<html  ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
<script type='text/javascript'>

function LoginController($scope) {
    $scope.user = {
        id: "",
        firstName: "",
        lastName: ""
    };
    $scope.logins = [];
    $scope.login = function () {
        $scope.logins.push($scope.user);
        console.log($scope.logins);
    };

}
</script>
</head>
<body>
  <div ng-controller="LoginController">
    <div>Hello {{ user.firstName }}</div>
    <input id="id" ng-model="user.id"></input>
    <input id="first" ng-model="user.firstName"></input>
    <input id="last" ng-model="user.lastName"></input>

    <input type="submit" ng-click="login()" value="Login"></input>
    <ul>
    <li ng-repeat="login in logins" >{{user.id + ', ' + user.firstName + ', ' + user.lastName}}</li>
    </ul>    

</div>
</body>
</html>

Answer №1

When working with a repeater, it's important to note that you cannot add the same object (a duplicate) that is already being used in the repeater. Instead, you should create a new object before adding it to the array.

For example, check out this code snippet:

If you want to see the full example, click on this link

$scope.logins.push({id:$scope.user.id, firstName: $scope.user.firstName, lastName: $scope.user.lastName});

In the provided HTML markup below, notice how we are creating a new object before pushing it into the logins array for the repeater to iterate through.

<!DOCTYPE html>
<html  ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
<script type='text/javascript'>

function LoginController($scope) {
    $scope.user = {
        id: "",
        firstName: "",
        lastName: ""
    };
    $scope.logins = [];
    $scope.login = function () {
        $scope.logins.push({id:$scope.user.id, firstName: $scope.user.firstName, lastName: $scope.user.lastName});
        console.log($scope.logins);
    };
$scope.selectUser= function(user){
$scope.user = user;
}
}
</script>
</head>
<body>
  <div ng-app ng-controller="LoginController">
    <div>Hello {{ user.firstName }}</div>
    <input id="id" ng-model="user.id"></input>
    <input id="first" ng-model="user.firstName"></input>
    <input id="last" ng-model="user.lastName"></input>

    <input type="submit" ng-click="login()" value="Login"></input>
    <ul>
    <li ng-repeat="login in logins" ng-click="selectUser(login)">{{login.id + ', ' + login.firstName + ', ' + login.lastName}}</li>
    </ul>    

</div>
</body>
</html>

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

A guide to defining a color variable in React JS

I am trying to use a random color generated from an array to style various elements in my design. Specifically, I want to apply this color to certain elements but am unsure how to do so. For example, I know how to make a heading red like this: const elem ...

Unable to retrieve JSON data using jQuery

When working with jQuery to retrieve JSON data, I encountered an issue. After storing the data in a variable named "ajaxResponse," attempting to access specific data points resulted in an error stating that ajaxResponse.blah is not defined. Interestingly, ...

Troubleshooting a Form Validation Issue with React's useState Hook

I am currently working on form validation for a project. The form includes two essential elements: a textbox for messages and a textbox for recipients. These elements are controlled by state.message (a string) and state.recipients (an array). The state var ...

Guide to configuring a robust schema and validation with joi

Currently in the process of setting up validation using the joi package, encountering syntax-related issues along the way. The schema in place is simple, checking for a valid number and verifying if the ID exists in the database. export default router.pos ...

Implementing a way to output a JavaScript script using PHP via AJAX

I need help with a JavaScript script that should be echoed when a certain condition is met. The issue arises when the file containing this script is called through Ajax by another page, as it fails to echo the <script>...</script> part. It seem ...

Tally each div individually and display the count within each div, instead of showing the total count across

I have come across various solutions that show the total number of certain special divs, such as: $('.someclass').length However, I am facing a different challenge. I want to sequentially count each div with a numerical sequence. For instance, ...

What is the process for modifying the headers of a post request in Express when

I have a Node/Express application and I'm looking to incorporate an image upload feature into an order form. While I can successfully use the action link in the HTML form to perform a POST request, I also want my JavaScript file associated with this ...

Increment numbers using XML elements

In my XML construction process, I start with a base XML and add elements like this: $(xml).find('PARENT').find('CHILDREN').each(function(i){ outputstr += '<lorem id="">' }) As the "parent" object appears mul ...

The Ajax function is unable to accept JSON data as input

I am trying to figure out why I am unable to access data from a JSON object (json.projects[i].projName) when calling it from within an AJAX function. Below is the code that demonstrates this issue: var json = JSON.parse(data); for (var i = 0; i < json ...

Arrow function utilized in string rendered component

Hello everyone, I could use some help with the following code snippet: rowRenderer = (e) => { debugger; return e.data?.fileName ? '<a class="documentLink" onclick={() => \'' + console.log('\ ...

Interactive PDFs that launch a new browser tab rather than automatically downloading

I am facing an issue with my web API that is returning a JSReport as an encoded byte array. Despite multiple attempts to read the byte array, I keep encountering either a black screen or an error message indicating "failed to download PDF". Interestingly, ...

Is Angular Translate susceptible to race conditions when using static files for multi-language support?

Currently utilizing angular translate with the static files loader for implementing multiple languages in my project. However, I've encountered a problem where the loading of language files sometimes takes longer than loading the actual view itself, l ...

What is the best way to extract numbers from a string using JavaScript?

I am working with a string in javascript that looks like this: var xyz= "M429,100L504.5,100L504.5,106L580,106L570,98M580,106L570,114"; My goal is to extract the numbers and store them in an array. I attempted the following code: var x=xyz.match(/\ ...

JavaScript Canvas - Preserve Image Transparency

I have been trying to download a snapshot of a canvas using the code below: var strMime = "image/png"; var canvas = document.getElementsByTagName('canvas')[0]; var link = document.createElement("a"); link.href = canvas.toDataURL( ...

Is it possible that only one number is printed when document.getElementById("demo").innerHTML = Math.ceil((Math.random()*10)-1); is executed?

How come the code document.getElementById(“demo”).innerHTML = Math.ceil((Math.random()*10)-1); is only displaying one number? function myFunction() { var bbb = document.getElementById("ilgis").value; for (i = 0; i <= bbb; i++) { //docum ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

The function responsiveTable does not exist

I recently added the following code to my aspx page: <script src="../Scripts/jquery.responsivetable.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#grdStudent').responsiveTable( ...

Custom cellRenderer prevents Ag Grid's autoHeight and wrapText features from functioning properly

I've been attempting to adjust the formatting of a long cell value by wrapping the text. According to the documentation, setting autoHeight=true and wrapText=true works fine without any cellRenderer components. However, when using a cellRendererFramew ...

Creating dynamic button names and detecting the pressed button in PHP

Right now, I am experimenting with PHP to create a unique project. This experiment is just a small part of a larger file that I am working on. Essentially, the aim is for the program to generate a series of submit buttons within a form, each assigned a dis ...

Angular 4 with Universal: Implementing 404 Status Code in Header for /404 Page Component

After researching and reviewing numerous StackOverflow inquiries, I have come to the conclusion that headers are derived from responses served by servers, making it a non-issue. I attempted to rectify the situation from my server.ts file but unfortunately ...