AngularJS Sign-In Page: A Seamless User Experience

Currently facing an issue: I am working on creating a login form where I need to validate if the username and password entered in the input fields match the values stored in my array of users.

var app = angular.module('myApplication', []);

app.controller('UserListCtrl', function ($scope) {   
  $scope.usersList = [    
      {
          name: 'Alex',
          pass: 2200201
      },
      {
          name: 'Michael',
          pass: 1231215   
      },
      {
          name: 'John',
          pass: 1232116   
      }
  ];

  $scope.checkInputs = function () {

      $scope.searchUser = {
          name: $scope.yourName,
          pass: $scope.yourPass
      };

      if ($scope.searchUser.name === $scope.usersList.name) {
          console.log($scope.searchUser.name);
      } else {
          console.log('You are not registered');
      }

  };
});

Here's how it looks in HTML:

<form ng-submit="checkInputs()">
        <input type="text" ng-model="searchUser.yourName"><br>
        <input type="text" ng-model="searchUser.yourPass">
        <input type="submit" class="button">
</form>

Answer №1

Kindly note: this response addresses the various errors found in the code provided in the query, such as:

  • verifying if a string is within an array of objects
  • managing AngularJS databinding between the view and the model

The code presented here should not be viewed as a reliable authentication solution.


I want to validate whether the username entered by the user in the input form matches the usernames stored in the users' array.

To accomplish this, you wrote

$scope.searchUser.name === $scope.usersList.name
. This approach will not work because usersList is an array of strings, not a single string. To check if a name exists in the usersList array, you can utilize the indexOf function.

The indexOf() method returns the first index at which a specified element can be found in the array, or -1 if it is not present.

1) Revise:

if ($scope.searchUser.name === $scope.usersList.name) {
    // ...
}

with

Solution 1: assuming you are using a library like lodash or underscore with a pluck function:

var userNames = _.pluck($scope.usersList, 'name');
if (userNames.indexOf($scope.searchUser.name) >= 0) {
    // ...
}

Solution 2: create your own pluck function:

var myPluck = function (propertyName, array) {
    return array.map(function(obj) {
        return obj[propertyName];
    })
}
var userNames = myPluck('name', $scope.usersList);
if (userNames.indexOf($scope.searchUser.name) >= 0) {
    // ...
}

2) Additionally, replace:

$scope.searchUser = {
    name: $scope.yourName,
    pass: $scope.yourPass
};

with

$scope.searchUser = {
    name: '',
    pass: ''
};

3) Finally, in the HTML template, update:

<input type="text" ng-model="searchUser.yourName"><br>
<input type="text" ng-model="searchUser.yourPass">

with

<input type="text" ng-model="searchUser.name"><br>
<input type="text" ng-model="searchUser.pass">

Answer №2

Check out the working jsfiddle link here

 <form  ng-submit="checkInputs(searchUser)">
            <input type="text" ng-model="searchUser.yourName"><br>
            <input type="text" ng-model="searchUser.yourPass">
            <input type="submit" class="button">
    </form>        



function formCtrl($scope){
         $scope.usersList = [    
          {
              name: 'Alex',
              pass: 2200201
          },
          {
              name: 'Michael',
              pass: 1231215   
          },
          {
              name: 'John',
              pass: 1232116   
          }
      ];

         $scope.checkInputs = function (credentials) {
             var auth = false;
             angular.forEach($scope.usersList, function(value){

                 if(value.name == credentials.yourName && value.pass == credentials.yourPass){
                     auth = true;
                 }
                 if(!auth){

                     $scope.message= "Access denied";

                 }
                 else
                 {
                     $scope.message= "Access granted";
                 }

             });

         }

    }

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

Is it possible to align the radio-button label above the radio-button in Angular Material 2?

Currently, I am utilizing angular material 2 (material.io) and attempting to position the label of the md-radio-button above the radio button itself. Here's an illustration: View Radio Buttons The official documentation mentions that you can easily ...

Error: The document is unable to detect any input values

I've been struggling with this issue for quite some time now and I can't seem to figure it out, no matter how hard I try. It seems that my input field is not capturing the value entered by the user for some unknown reason. Let me share the code ...

Enhancing Rails: Tailoring the flash message to suit individual needs

I am embarking on my journey with ruby on rails and could use some guidance with the following scenario. In the application.html.erb file, flash messages are configured to fade out after a few seconds by default. <div id="message" class="modal alert a ...

Transform the date format from yyyy-MM-dd'T'HH:mm:ss.SSS'Z' to dd-mmm-yyyy with the help of JavaScript

I am looking to convert date format from yyyy-MM-dd'T'HH:mm:ss.SSS'Z' to dd-mmm-yyyy when the dates are retrieved from a JSON object. Currently, I am utilizing the ng-csv plugin to download this JSON data, which is working properly. How ...

Utilizing a PHP-scripted multidimensional array in an AJAX success function

I've encountered an issue while trying to access a multidimensional array passed to my AJAX success function. Here's how I'm sending the data: $response = array(); $response['message']['name'] = $name; $response['m ...

In Node.js, the `res.send()` function is called before the actual functionality code is executed

As a newcomer to node js, I am currently working on an app where I query the MySql DB and process the results using node js. One issue I have encountered is that if my initial query returns null data, I then need to perform another query and further proc ...

The `Click()` functionality experiences malfunction in Protractor automation scripts

I am currently automating my tests using Protractor and Appium for an AngularJS website with the Jasmine framework in an iPad simulator. Although the sendkeys() function is working fine for entering the username and password, I am facing issues when clicki ...

Using JavaScript to transfer input field text into a textarea

How can I use JavaScript to insert a text or string from an input field into a text area that already contains some text? The inserted text should appear at the cursor position, and I also need a button for inserting. Is there a way to achieve this functio ...

Creating a horizontal line with text centered using Angular Material's approach

Implementing Angular Material, my objective is to design a horizontal line with a word positioned in the center. Similar to the one showcased here. I experimented with this code, achieving a close result, but I aim to align the lines vertically to the mid ...

Modify the contents of an array within a string using JavaScript

let message = "hello https://ggogle.com parul https://yahoo.com and http://web.com"; let url = ["https://ggogle.com", "https://yahoo.com", "http://web.com"]; I'm trying to replace all URLs in the 'message' array with "***" from the 'ur ...

Retrieving the file name from the line number within the trace stack or Error object

I'm working on enhancing my error handling in Node.js/express. Does anyone know a method to retrieve the filename and line number where an error occurs in my code? error-handler.js, utilizing console.trace, only handles errors at the route level...n ...

Angular Js powered admin control panel

Explore the SB Admin Angular by Start Angular My current project involves setting up an admin dashboard on a Windows system. However, I have encountered some issues during the installation process using npm install An error message can be found here ...

Implementing a collapsible menu feature in Bootstrap 3 when clicked

Experiencing an issue with a Bootstrap menu where I want the menu to collapse after clicking on one of the sections. This is the HTML code: <div class="container" id="home"> <nav class="navbar navbar-default navbar-fixed-top" role="navig ...

Extra brackets appear when retrieving JSON data

In my code, I am attempting to extract data from a JSON file. The JSON data does not have any brackets, just an array separated by commas. However, when I retrieve the data using $scope, an extra square bracket is added outside of my output. Here is a demo ...

Create a unique shader in Three.js that remains unaffected by the fog effect

I have implemented a custom shader to add glow to a sphere on my scene. However, I noticed that the fog in the scene affects the sphere but not the glow. When I zoom out, the sphere disappears but the glow remains visible. Is there a way to make the fog ...

When a user clicks on a child element of an anchor tag, the function will

Is it possible to return a specific function when a user clicks on a child of an anchor element? <a href="/product/product-id"> I am a product <div> Add to favorites </div> </a> const handleClick = (event) =>{ ...

Tips for implementing a delay in jQuery after an event occurs

I am working with text boxes that utilize AJAX to process user input as they type. The issue I'm facing is that the processing event is quite heavy. Is there a way to make the event wait for around 500ms before triggering again? For example, if I type ...

Employ AngularJS UI-Router for creating a summary page

My web application is built using AngularJs with ui-router. The app contains multiple forms, with the number of forms varying depending on the user's needs. Each form has its own unique ui-route state, allowing users to navigate through and submit in ...

What is the process for updating the ID within a Select2 ajax script function?

I am facing an issue with my select2 ajax script. The unique_ID in my table field is named "no", which is causing me to be unable to select an item in Select2 drop down. However, when I changed the name of my database table field from "no_donatur" to "ID", ...

Looking to identify the type of a adorned class in Typescript?

Consider the following scenario: return function IsDefined(object: any, propertyName: string) { .... ] We then go ahead and decorate a property like this: class Test { @IsDefined() p1: String = ""; } Now, when we execute a test inside the ...