article

Friday, November 26, 2021

AngularJS Show Alert with Timeout

AngularJS Show Alert with Timeout

index.html
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>AngularJS Create Alert with Timeout</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <style type="text/css">
    	.bottom-left{
			display:block;
			position:absolute;
			bottom:50px;
			left:50px;
		}
    </style>
</head>
<body  ng-app="app" ng-controller="myController">
<div class="container">
    <h1 class="page-header text-center">AngularJS Show Alert with Timeout</h1>
    <div class="row">
	    <div class="col-sm-4 col-sm-offset-4">
	    	<div class="panel panel-default">
	    		<div class="panel-body">
	    			<form name="myForm" ng-submit="submitForm()">
	    				<div class="form-group">
		    				<label>User Name:</label>
		    				<input type="text" class="form-control" ng-model="user.username" required>
		    			</div>
		    			<div class="form-group">
		    				<label>Password:</label>
		    				<input type="password" class="form-control" ng-model="user.password" required>
		    			</div>
	    				<button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid"><span class="glyphicon glyphicon glyphicon-send"></span> Submit</button>
					</form>
	    		</div>
			</div>		
		</div>
	</div>
</div>
<div class="alert alert-success text-center bottom-left" ng-show="success">
	<button type="button" class="close" ng-click="closeAlert()">×</button>
   	<span class="glyphicon glyphicon-check"></span> {{ message }}
</div>
<script>
var app = angular.module('app', []);
app.controller('myController', function($scope, $timeout){
    $scope.success = false;

    $scope.submitForm = function(){
    	//success request
    	$scope.success = true;
    	$scope.message = 'Successfully Login'; 
    	
    	//after 5 sec call to close the alert
    	$timeout( function(){
            $scope.closeAlert();
        }, 5000 );
    }

    $scope.closeAlert = function(){
    	$scope.success = false;
    }
});
</script>
</body>
</html>

Related Post