In this tutorial you will learn about the Simple User Login Example in AngularJS and its application with practical example.
Simple User Login Example in AngularJS
In our previous article, we have learned how to create simple user registration form In AngularJS . Once a user is registered on the website can be obtain login credentials(username and password). In this article, we will learn how to to create simple login form in AngularJS. We will create a simple login page where user input their username and password, if the user is authenticated successfully they will be redirected to a user home page. If authentication fails, the user is notified with an error message.
Project’s Directory Structure :-
AngularJS Application Layout
Before starting with this tutorial we will create base layout i.e. index.html file where all our application views will be loaded. Let’s create index.html file and put the following code in it –
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!doctype html> <html ng-app="myApp" > <head> <meta charset="utf-8"> <title>AngularJS Simple Login Example - W3Adda</title> <script>document.write('<base href="' + document.location + '" />');</script> <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"> <script src="http://code.angularjs.org/1.2.13/angular.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script> <script src="app.js"></script> <script src="loginController.js"></script> <script src="homeController.js"></script> <script src="loginService.js"></script> </head> <body> <div class = "container" style="width:675px;text-align:center;"> <h2>AngularJS Simple Login Example - W3Adda</h2> <div ui-view></div> </div> </body> </html> |
AngularJS Application
Every angular application starts from creating a angular module. Module is a container that holds the different parts of your application such as controllers, service, etc. In this step we will create a main javascript file app.js that will hold all the required configuration to run an angularjs application. We will also configure application routes in this file using AngularJS UI Router module. Let’s create app.js file and put the following code in it –
app.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
(function() { var app = angular.module('myApp', ['ui.router']); app.run(function($rootScope, $location, $state, LoginService) { console.clear(); console.log('running'); if(!LoginService.isAuthenticated()) { $state.transitionTo('login'); } }); app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('login', { url : '/login', templateUrl : 'login.html', controller : 'LoginController' }) .state('home', { url : '/home', templateUrl : 'home.html', controller : 'HomeController' }); $urlRouterProvider.otherwise('/login'); }]); })(); |
The app variable is initialized as angular module and named as “myApp”, notice that we have used ng-app directive in index.html file to bind the angular application to a container in base layout file. It is important to use the same module name to bind using ng-app directive.
AngularJS Routing
Since we are making a single page application and we don’t want any page refreshes. Here we have used Angular’s UI Routing capabilities to setup single page application.We are using ui.router module for that, notice that we have added ui.router as a part of the parameter passed to our angular module. The ui.router module provides routing, deeplinking services and directives to our angular applications. Here, we are using $urlRouteProvider in app.config to configure our application routing. As you can see in routing configuration, every route you specify have a template file and a controller attached to it.
AngularJS Template
Now, in this step we will create login and home page template files for our angularjs simple login application. Let’s create login.html and home.html files and put the following code in it respectively.
login.html
In login page, we have two input fields ( UserName and Password) with a login button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="col-md-12"> <form ng-submit="formSubmit()" class="form"> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" ng-model="username" placeholder="username" required=""/> </div> <div class="form-group"> <input type="password" class="form-control" ng-model="password" placeholder="password" required=""/> </div> <div class="form-group"> <button type="submit" class="btn btn-info">Login</button><br> <span class="text-danger" style="color:red">{{ error }}</span> </div> </div> </form> </div> |
home.html
Once a user is successfully logged in the home page (home.html) will be loaded. Here, we have simple welcome message along with a logout button.
1 2 3 4 5 |
<div class="col-md-12" style="width:500px;"> <div align="right"><a ui-sref="login">Logout</a></div> <h4>Welcome {{user}}! </h4> <p><strong>User Dashboard</strong></p> </div> |
AngularJS Controller
As you can see in routing configuration, every route you specify have a controller attached to it. Angularjs controller hold the actual business logic attached with the route. In this step we will create separate controller files for login page and home page. Let’s create loginController.js and homeController.js file and put the following code in it respectively.
loginController.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var app = angular.module('myApp'); app.controller('LoginController', function($scope, $rootScope, $stateParams, $state, LoginService) { $rootScope.title = "AngularJS Login Sample"; $scope.formSubmit = function() { if(LoginService.login($scope.username, $scope.password)) { $rootScope.userName = $scope.username; $scope.error = ''; $scope.username = ''; $scope.password = ''; $state.transitionTo('home'); } else { $scope.error = "Incorrect username/password !"; } }; }); |
homeController.js
1 2 3 4 5 |
var app = angular.module('myApp'); app.controller('HomeController', function($scope, $rootScope, $stateParams, $state, LoginService) { $scope.user = $rootScope.userName; }); |
AngularJS Services
Here, we will create a simple authentication service that authenticate user with default login credentials. As the user enters login credentials and clicks on the login button we authenticate the user and redirect them to user home page. We store the user data in angularjs scope object and binding it to the variable. If can also authenticate user with their registered credentials in database using a webservice or API that talks to database server. For now we will be creating a simple authentication service that authenticate user with default login credentials. Let’s create a loginService.js and put the following code in it –
loginService.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var app = angular.module('myApp'); app.factory('LoginService', function() { var admin = 'admin'; var pass = 'admin'; var isAuthenticated = false; return { login : function(username, password) { isAuthenticated = username === admin && password === pass; return isAuthenticated; }, isAuthenticated : function() { return isAuthenticated; } }; }); |
Run AngularJS Application
Now start the application server and visit the application to view the output.
Login Page :-
Home Page :-