Is there a more effective approach to designing a login screen?

I am just starting out with angular js and this login page is my first step. I have created a basic login form, but when I click on the login() button, the form() does not get submitted and it keeps showing an error message saying "invalid username and password". I tried looking for solutions in other blogs but couldn't quite understand them.

Here is the code:

HTML :

<div class="package" ng-controller="credentials">
    <form ng-submit="loginform()"  class="ng-scope ng-pristine ng-valid">
      <label form="emailinput">Email</label>
      <input type="text" class="form-control ng-pristine ng-valid" ng-model="username">
      <label form="pwdinput">Password</label>
      <input type="password" class="form-control ng-pristine ng-valid" ng-model="password">
    <div>
      <button type="cancel" class="btn" ng-click="toggle_cancel()">Cancel</button>
      <button class="btn btn-primary" ng-click="">Login</button>
    </div><br/>
      <span class="text-danger">{{ error }}</span>
    </form>

Angular JS :

var app = angular.module('logapp',['ngRoute']);
app.config(function($routeProvider){
            $routeProvider
                .when('/login',{
                    templateUrl : "login.html",
                    controller : "loginctrl"
                })
                .when('/home',{
                    templateUrl : "home.html",
                    controller : "homectrl"
                });
            $routeProvider.otherwise({ redirectTo: '/login'});
        });

 app.controller('credentials',['$scope','$route','$http','$window',function($scope,$route,$http,$window){
   $scope.templates =
                [
                    { url: 'login.html' },
                    { url: 'practice.html'}
                ];
                    $scope.template = $scope.templates[0];
                    $scope.loginform = function (username, password) {
                if ( username === 'admin' && password === '1234') {
                    authentication.isAuthenticated = true;
                    $scope.template = $scope.templates[1];
                    $scope.user = username;
                } else {
                    $scope.error = "Invalid username and password";
                };
              };

      app.factory('authentication', function() {
                return {
                isAuthenticated: false,
                user: null
              }
        });

    }]);

Answer №1

Make sure to include the 'authentication' factory in your controller before using it.

app.controller('credentials',['$scope','$route','$http','$window', function($scope,$route,$http,$window, authentication){

Remember to assign the username and password to $scope variables like so:

$scope.username === 'admin' && $scope.password === '1234'

By doing this, you will set the variable isAuthenticated in the factory to true.

You can find the updated code here

Answer №2

Ensure to include both your username and password in the scope for a better result. Consider this alternative approach:

$scope.username = "";
$scope.password = "";
$scope.loginform = function () {
if ( $scope.username === 'admin' && $scope.password === '1234') {

It is highly advised to follow this tutorial for more insights:
https://docs.angularjs.org/tutorial

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

Strategies for handling user typos in a JavaScript prompt

Hi there! Just wanted to say that I'm new to this website, so please forgive any posting mistakes I might make. I'm currently taking a web technology class where we're learning JavaScript. In a previous lesson, we covered HTML5 and CSS. Our ...

Clicking on the checkbox will trigger the corresponding table column to disappear

Upon clicking the filter icon in the top right corner, a menu will open. Within that menu, there are table header values with checkboxes. When a checkbox for a specific value is selected, the corresponding table column should be hidden. I have already impl ...

Storing information from a table into LocalStorage

$('.new_customer').click(function () { var table = $("table"); var number = table.find('tr').length; table.append('<tr id="' + number + '"><td><input type="button" class="btn btn-success btn-xs" ...

AngularJs, Dynamically Adjusting URL Parameters Based on User Input

I am currently working on integrating my ASP.NET Web API with AngularJs. I am facing an issue where I need to pass optional parameters to the URL based on user input from 2 HTML text boxes, but I am unsure of how to accomplish this. Below is a snippet of ...

Encountering an issue while attempting to input a URL into the Iframe Src in Angular 2

When I click to dynamically add a URL into an iframe src, I encounter the following error message: Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D' To ensure the safety of the ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

Utilize identical animations across various elements

I have a canvas animation in JavaScript that is currently limited to one canvas element with the id "stars". I want to be able to use this animation multiple times without repeating the code. Is there a way to add a class for the canvas elements instead of ...

Sending data to a server using the select element within a form

I am dealing with a controller that looks like this: $scope.disciplines = disciplines; $scope.discipline = disciplines[0]; This controller contains an array. Within my form, I have the following elements: <form class="form-horizontal" ng-submi ...

Attempting to dynamically insert a new row into a table using jQuery, with the added condition of limiting the total number of rows to four

I'm facing an issue with a table that has no rows. I want to dynamically add rows by clicking an anchor tag, with a limit of 4 rows. When the limit is reached, I need to display an alert message saying "only 4 rows allowed." However, currently, it kee ...

Unable to assign a className to a personalized React component - troubleshooting needed!

I have a component that relies on another component. I am trying to pass CSS positioning from the outer component to the inner one by using the following code: import OptionsMenu from './OptionsMenu' import { withStyles } from 'material-ui/ ...

Searching for components in Python Selenium - a missing element

Encountered a strange issue with the "find_elements_by_css_selector" function in Selenium. Despite expecting to retrieve 10 elements, only 9 are returned consistently across various page examples. Interestingly, when testing the same selector using JavaScr ...

What is the best way to update a nested property in an object?

Consider the following object: myObject{ name: '...', label: '...', menuSettings: { rightAlignment: true, colours: [...], }, } I want to change the value of rightAlignment to fals ...

Textarea generated on-the-fly without any assigned value

My goal is to enable users to edit the text within a paragraph on a website. I am attempting to replace the <p> tags with <textarea> tags using the .replaceWith() function. However, when I try to retrieve the value of the textarea, it comes bac ...

AngularJS animation fails to activate

I've been working on a simple AngularJS application and I'm trying to add animations between my views. However, for some reason, the animation is not triggering despite following the tutorial on the AngularJS website. There are no errors in the c ...

Illumination causes surfaces to transform

In my simple scene, I have a ground and an interesting light source. However, when the light hits certain meshes, it creates some strange effects. The shadows are being cast correctly, but the other meshes affected by the light are showing unusual results. ...

Retrieve the list of device tokens for the APNS service

Is it possible to retrieve a list of all device tokens on which my app is installed through an APNS endpoint? I am aware of the feedback service that provides the status of devices to whom messages are sent, but I believe this is only after the message ...

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

Receive real-time updates on the progress of a lengthy post by utilizing Angular's $http feature

I am utilizing Angular to send a request to an MVC controller that then proceeds to send multiple emails, resulting in a significant delay. Is there a way to receive status updates from the server as each batch of emails is sent (e.g. every 50 emails)? He ...

Having trouble updating a text field on an event using JavaScript - value not defined

When I change the select option, my goal is to dynamically set the value of the input using JavaScript. However, I am encountering an issue where the value becomes undefined. Below is a snippet from my HTML (JSP) file: <body> <center>< ...

Unable to make colors appear in HTML5 canvas using .fillStyle

Trying my hand at canvas for the first time to create a game. I have an image displaying, but strangely the fillStyle method doesn't seem to be working as expected (the canvas background remains white in Google Chrome). Just a note that in my code, t ...