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

Exploring the wonders of Node.js, Redis, and Express.js while navigating through the enchanting world of Asynchronous

Hello there, I must confess that this is a whole new realm for me... Here is what we've got: app.get('/user/:user_id/followings', function(req, res) { var response = {} , userId = req.params.user_id , ids = req.param(' ...

Timepicker Bootstrapping

I've been searching for a time picker widget that works well with Bootstrap styling. The jdewit widget has a great style, but unfortunately it comes with a lot of bugs. I'm on a tight deadline for my project and don't have the time to deal w ...

Unable to load routes from ./app.js in the file ./src/routes/index.js

Just dipping my toes into the world of nodejs. I recently moved all my routes from app.js to a separate file located at PROJECT_DIR/src/routes/index.js. However, when I try to open the page in my browser, it displays "Cannot GET /wines". Below are snippets ...

Determine whether a subdomain is present within an ajax file in php

Looking for assistance with checking the existence of a 'Subdomain' in a file called '\example\sites'. Here's the code: $form = array() ; $form['name'] = "install"; $form['action'] = "?step=2"; $for ...

The polygon array feature is not functioning as expected in the Google Maps API

I'm currently facing an issue with a code that is supposed to draw polygons from an array in the Google Maps API, but unfortunately, it doesn't seem to be working as expected. <!DOCTYPE html> <html> <head> <script src ...

I am unable to access Angular $scope in the HTML Template, although I can view it in the console log

I have been following some online tutorials and using the angularjs-template to start learning Angular. However, I am facing an issue where the page (html template) is not updating with the controller. It seems like there is a problem in how I've set ...

Challenge with Angular dependencies: Transitioning from Windows to Linux

I'm facing a challenge with hosting an Angular application on Linux for a client. The application runs smoothly on Windows where the customer develops it. My NodeJS version is 19. Upon running npm install, I encountered this error message: npm notice ...

Encountered an Unhandled Runtime Error in NextJs: Invalid Element Type

Attempting to build an Instagram clone following a YouTube tutorial from a year ago has led to various errors arising from nextjs14. I have managed to resolve all of them except for one particular issue: Error: Element type is invalid - expected a string ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

Sending a post request using an AngularJS service

I have implemented the following code in my application. The dataService holds all the $http requests in my app. In the controller, I am using this function to call a Web Api service which returns the correct response. However, when the function customer ...

Extract reference value from an HTML element

Is there a way to access the ref prop from an HTML element using Testing Library React? My current code snippet is as follows: it('element container ref should be null if prop noSwipe is passed', () => { const onCloseMock = jest.fn() ...

When I click the back button on my mouse in React, it returns JSON data instead of HTML and CSS

I am working on a web application with two pages: a menu and orders. When I navigate from the orders page to the menu page and click the back button, I receive JSON data instead of the HTML page. The data loads correctly, but the page does not display the ...

Develop a fresh scope attribute within a directive in AngularJS

The value remains hidden in the DOM, and I am experimenting to see if this approach will work successfully. My goal is to establish a new scoped value within the directive and display it on the DOM. app.directive("rest", ["restFactory", function($rest){ ...

Prevent unnecessary clicks with Vue.js

In my vue.js application, there is a feature to remove items. The following code snippet shows the div element: <div class="ride-delete" @click="delete"> <p>Delete</p> </div> This is the function used to handle the click ...

Troubleshooting issues with AngularJS $watch not triggering properly

Even though Deep watch has been activated in the factory, it is not triggering. What steps can be taken to resolve this issue and ensure that an event is triggered when the 'name' value changes? Javascript Code: var app = angular.module('a ...

How can values be passed to child components in Vue when using component tags for dynamically switching components?

Is there a way to pass values to children components in Vue when using the component tag? It appears that I am unable to pass values to a child component using the component tag without using v-if: <component :is="showNow"></component> ...

Exploring the location where an XMLHttpRequest/Ajax link is executed

I am relatively new to the world of Ajax/XMLHttpRequest and I am currently trying to wrap my head around its functionality. My current project involves developing an inventory program that essentially allows users to add tools to a digital box. On the mai ...

When using Firestore in Android, I encounter a nodejs error regarding headers being sent prematurely

Currently, I am utilizing a webview in order to display content from a nodejs server. While requesting a page works as expected, accessing firestore results in an error where it seems like nodejs is attempting to resend the page. Below is the code for an a ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

Non-IIFE Modules

Check out this discussion on Data dependency in module I have several modules in my application that rely on data retrieved from the server. Instead of implementing them as Immediately Invoked Function Expressions (IIFEs) like traditional module patterns ...