In this article I will explain how to display (show) JavaScript Alert message box on Button click using AngularJS ng-click directive.
AngularJS makes use of global variable named $window which is a reference of the JavaScript window object in order to access the JavaScript window functions such as Alert.
Displaying JavaScript Alert using AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML TextBox and a Button to which ng-click attribute has been assigned.
When the Button is clicked, the ShowAlert function of the Controller gets called, which displays the value of Name TextBox using JavaScript Alert message box.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.ShowAlert = function () {
if (typeof ($scope.Name) == "undefined" || $scope.Name == "") {
$window.alert("Please enter your name!");
return;
}
$window.alert("Hello " + $scope.Name);
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Name" />
<br />
<br />
<input type="button" value="Show Alert" ng-click="ShowAlert()" />
</div>
</body>
</html>
Screenshot
Demo
Downloads