Create Alert with Timeout using Angular JS
Submitted by nurhodelta_17 on Sunday, January 14, 2018 - 21:09.
Getting Started
I've used CDN for Bootstrap and Angular JS so you need internet connection for them to work.index.html>
This is our index which contains our form that upon submit, an alert will popup.- <!DOCTYPE html>
- <html lang="en" ng-app="app">
- <head>
- <meta charset="utf-8">
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
- <style type="text/css">
- .bottom-left{
- display:block;
- position:absolute;
- bottom:50px;
- left:50px;
- }
- </style>
- </head>
- <body ng-controller="myController">
- <div class="container">
- <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">
- <input type="text" class="form-control" ng-model="user.firstname" required>
- </div>
- <div class="form-group">
- <input type="text" class="form-control" ng-model="user.lastname" required>
- </div>
- <div class="form-group">
- <input type="text" class="form-control" ng-model="user.address" required>
- </div>
- </form>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="alert alert-success text-center bottom-left" ng-show="success">
- </div>
- </body>
- </html>
angular.js
This contains our angular.js script wherein upon showing our alert, using $timeout, we have set to close the alert after 5 secs.- var app = angular.module('app', []);
- app.controller('myController', function($scope, $timeout){
- $scope.success = false;
- $scope.submitForm = function(){
- //if you want to send request you can do it here
- //then do this on success request
- $scope.success = true;
- $scope.message = 'User added successfully'; //->put whatever message you want
- //after 5 sec call to close the alert
- $timeout( function(){
- $scope.closeAlert();
- }, 5000 );
- }
- $scope.closeAlert = function(){
- $scope.success = false;
- }
- });
Add new comment
- 292 views