Looking to dynamically display users added to an array in a table using Angular and JavaScript?

As a newcomer to javascript and angularjs, I recently attempted to build a table that would display all users in an array dynamically as new users are added through a form. However, each time I run my code, I encounter the error message "Fill out the entire form!". I am seeking guidance on what might be going wrong with my implementation and how I can rectify it.

Thank you in advance for your assistance!

My HTML:

<table>
<tr>
<td colspan="5" class="align-center"><input type="text" placeholder="Search Users" class="search-users" ng-click="userSearch"/></td>
</tr>
<tr>
<td><input type="text" placeholder="First Name" class="add-user" id="formFirstName" /></td>
<td><input type="text" placeholder="Last Name" class="add-user" id="formLastName" /></td>
<td><input type="text" placeholder="Race" class="add-user" id="formRace" />    </td>
<td><input type="text" placeholder="Class" class="add-user" id="formClass" /></td>
<td><input type="text" placeholder="Faction" class="add-user" id="formFaction" /></td>
</tr>
<tr>
<td colspan="4" class="align-right error-field" id="errorField"></td>
<td colspan="1" class="align-right"><button type="button" class="add-user" ng-click="addUser()"/> Add </button></td>
</tr>
</table>

My Javascript/Angular:

$scope.jsFirstName = document.getElementById('formFirstName').value;
$scope.jsLastName = document.getElementById('formLastName').value;
$scope.jsRace = document.getElementById('formRace').value;
$scope.jsClass = document.getElementById('formClass').value;
$scope.jsFaction = document.getElementById('formFaction').value;
$scope.jsID = users.length;
$scope.addUser = function () {
    $scope.character = {};
    $scope.character.id = $scope.jsID+1;
    $scope.character.firstName = $scope.jsFirstName;
    $scope.character.lastName = $scope.jsLastName;
    $scope.character.faction = $scope.jsFaction;
    $scope.character.class = $scope.jsClass;
    $scope.character.race = $scope.jsRace;

    if ($scope.jsFirstName.length === 0 || $scope.jsLastName.length === 0 || $scope.jsFaction.length === 0 || $scope.jsClass.length === 0 || $scope.jsRace.length === 0) {
        document.getElementById('errorField').innerHTML = "Fill out the entire form!";
    } else {
        users.push(character);
    }

};

});

Answer №1

When using AngularJS, it is recommended to utilize the ng-model directive for passing data from the view to the controller instead of manually handling it with Javascript. Avoid using document.getElementById within a controller.

To implement these changes in your code:

  1. Add the ng-model directive in each input type.
  2. Group all the form data into an object and use ng-model.

Example:

<td><input type="text" placeholder="First Name" class="add-user" ng-model="user.formFirstName" id="formFirstName" /></td>

Create a user object and pass this object using ng-click="addUser(user)".

Working Example:

var app = angular.module('myApp',[]);
app.controller('userController',function($scope) {
    $scope.usersData = [];
    $scope.addUser = function(user) {
      $scope.usersData.push(user);
      $scope.user = {};
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="userController">
<table>
<tr>
<td><input type="text" placeholder="First Name" class="add-user" ng-model="user.formFirstName" id="formFirstName" /></td>
<td><input type="text" placeholder="Last Name" class="add-user" ng-model="user.formLastName" id="formLastName" /></td>
<td><input type="text" placeholder="Race" class="add-user" ng-model="user.formRace" id="formRace" />    </td>
<td><input type="text" placeholder="Class" class="add-user" ng-model="user.formClass" id="formClass" /></td>
<td><input type="text" placeholder="Faction" class="add-user" ng-model="user.formFaction" id="formFaction" /></td>
</tr>
<tr>
<td colspan="1" class="align-right">
<input type="button" class="add-user" ng-click="addUser(user)" value="Add User"/>
</td>
</tr>
</table>
<table>
<tr>
  <td>First Name</td>
  <td>Last Name</td>
  <td>Race</td>
  <td>Class</td>
  <td>Faction</td>
</tr>
<tr ng-repeat="users in usersData">
  <td>{{users.formFirstName}}</td>
  <td>{{users.formLastName}}</td>
  <td>{{users.formRace}}</td>
  <td>{{users.formClass}}</td>
  <td>{{users.formFaction}}</td>
</tr>
</table>
</div>

Answer №2

If you're using Angular, it's important to avoid certain practices.

Let's consider a scenario from your code: FirstName :

<td><input type="text" id="formFirstName" ng-model="firstName" /></td>
<!-- Other similar lines -->

<td ng-bind="errorField"></td>
<!-- Alternatively -->
<td>{{errorField}}</td>

Since you have a controller, you can handle this in the following way:

$scope.addUser = function() {
    $scope.character = {};
    $scope.character.firstName = $scope.firstName;
    // Other similar lines

    if($scope.firstName === "") { // Additional conditions
        $scope.errorField = "Please complete the form";
    }
}

This is precisely why Angular was created.

Answer №3

When incorporating angular, make sure to utilize 2-way data binding by adding ng-model="fromFirstName" to your inputs. Set up a local variable in your controller like var firstname = $scope.formFirstName. With this setup, any changes made in real time will automatically reflect in both your views and models. To ensure input validation, check for emptiness when the user clicks the button. This approach should guide you through the process effectively.

Answer №4

Give this code a try:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<script>
var app = angular.module("myusersList", []);
app.controller("myCtrl", function($scope) {
    $scope.users = [{fname:"John",lname:"Doe",class:"12"},{fname:"Jane",lname:"Smith",class:"11"}];
    $scope.addUser = function () {
        var newUser = {};
        newUser.fname=$scope.fname;
newUser.lname=$scope.lname;
newUser.class=$scope.class;
        $scope.users.push(newUser);
    }
});
</script>

<div ng-app="myusersList" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="data in users">First Name : {{data.fname}} last Name : {{data.lname}} class : {{data.class}}</li>
  </ul>
  <input ng-model="fname">
  <input ng-model="lname">
  <input ng-model="class">
  <button ng-click="addUser()">Add</button>
</div>

<p>Start typing in the input fields to add new users.</p>

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

What are the benefits of installing both libraries A (react-router) and B (react-router-dom) together, especially when library B relies on library A for functionality

I am currently exploring the necessity of explicitly specifying all dependencies in the packages.json file. For instance, when I want to utilize the react-router library. According to the official documentation: npm install react-router@6 react-router-d ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

AngularJS: Issue with inputMask functionality within an angularJS table

Within my ng-repeat table, I have two date fields. Here is the code snippet: <tr ng-repeat="ol in orderLines"> <td> <input class="audioStartTime" type="text" ng-model="ol.AudioStartTime"/> </td> <td> ...

Updating the state after receiving API results asynchronously following a function call

I am attempting to update the state asynchronously when my fetchWeather function is executed from my WeatherProvider component, which calls an axios request to a weather API. The result of this request should be mapped to a forecast variable within the fet ...

attempting to link to an external style sheet hosted on Amazon S3

I am working on creating a widget or snippet of a website that can easily be added to another webpage by including a script tag for my JavaScript file hosted on Amazon S3 and a div element where content will be inserted. Even though I have uploaded the C ...

Add the JavaScript files to the components

I am working on integrating an admin template into my Angular2 project (version 2.1.0) which is already equipped with Bootstrap, jQuery, and jQuery plugins. Since there are numerous jQuery plugins and JS files involved, I am faced with the challenge of ho ...

Struggling with getting the JavaScript, scss, and CSS television animation to turn on and off properly? Seeking assistance to troubleshoot this

After finding this javascript code on Codepen and seeing that it worked perfectly in the console there, I tried to run it on my computer with jQuery but it didn't work outside of Codepen. Even when attempting to use it on JSfiddle or compile the SCSS ...

Tabbed horizontal slider

I am trying to combine two scripts in order to create a tab-based system with a scrollbar located at the bottom of the content. I have merged the following Ajax tabs: with this slider: However, when I open the slider's tab, I am unable to move the s ...

What might be preventing combineLatest from executing?

Currently, I am attempting to run a block of code utilizing the combineLatest function. Within my translation library, there exists an RXJS Observable that is returned. Imported as individual functions are combineLatest, map, and tap. combineLatest(this. ...

Using Typescript to create a Checkbox Grid that displays pipe-delimited values and implements a custom validation rule

I am currently working with a checkbox grid that contains pairs of AccountIds (consisting of x number of digits) and file names separated by a pipe delimiter. The file names are structured to always begin with either PRC or FE followed by a varying combin ...

Sending a sound recording to the express js server with the help of multer

I'm currently working on a project where I need to record audio and save it in my local directory (uploads folder) using express js and multer. The recording part is working fine with mic-recorder-to-mp3, but I'm facing an issue with saving the r ...

The JavaScript code is attempting to execute a PHP script, however, I am struggling to parse the JSON data returned for use in the

As a novice, I am in the process of creating a JavaScript function that calls a PHP script every second. The PHP script retrieves values from MySQL DB, encodes them into JSON, which is then decoded by JS to display them on an HTML page. I have two queries ...

AngularJS is throwing an error claiming that the controller is not defined and is not a function

Struggling to create a basic angular application, every time I attempt it, I encounter this issue and can never find a solution. The content of App.js is as follows: angular.module('Euclid', ['ui.bootstrap', 'ngRo ...

Suggestions to update arbitrary content at a 5-second interval in Vue using Nuxt.js

As a Vue beginner, I am facing an issue with changing random text every 5 seconds while the page is loading. <template> <section class="container"> <h1 class="title"> Welcome {{ whois }} </h1> </section&g ...

Using local variables from an external HTML file within an AngularJS directive template

Just making sure I am wording my question correctly, but I have not been able to find any information on this specific topic. Imagine I have an AngularJS directive that looks something like this: angular.module( 'example', [] ).directive( ...

Using AngularDart: Maximizing Efficiency with Dual ng-repeat Expressions in a Single Tag

I am looking to create a grouped table that resembles the following structure: Customer Site ------------------------------ Customer 1 Site 1.1 Site 1.2 Site 1.3 Customer ...

Make the adjustment from an H1 tag to an H2 tag with the help of

I need assistance with changing the HTML code from using an <h1> tag to a <h3> tag, using Vanilla JavaScript. Here is the code snippet in question: <h1 class="price-heading ult-responsive cust-headformat" data-ultimate-target=" ...

I'm wondering why myDivId.toggle() is functioning properly but myDivClass.toggle() is not working as expected

Using JQuery's toggle() function, I have been able to hide and show some DIVs successfully. Recently, I discovered relationships between certain DIVs that allowed me to group them into a class. I decided to try toggling the entire class rather than ...

AngularJS nested ng-repeat for displaying multiple checkboxes

I have a list generated with ng-repeat that displays category headings in myJSON.mylist followed by each subitem within each category. How can I modify this list to display checkboxes instead, allowing only subitems to be selected? <ul ng-repeat="s in ...

The webpage encountered an issue while trying to load a resource: the server returned a 500 (Internal Server Error) status message, preventing the submission of the data

When I use AJAX jQuery to send data via POST, the input name does not get sent and the database shows NULL as the answer. Thank you for any assistance. Below is my JQuery code: $('#btn-save').click(function(){ $.ajax({ url: "<? ...