In this article I will explain how to display (show) JavaScript Confirm dialog 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 Confirm.
Displaying JavaScript Confirm dialog 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 SPAN to which ng-bind directive has been set and a Button to which ng-click attribute has been assigned.
When the Button is clicked, the ShowConfirm function of the Controller gets called, which displays the JavaScript Confirm dialog box and based on whether user clicked OK or Cancel, the respective message is displayed in HTML SPAN.
<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.ShowConfirm = function () {
if ($window.confirm("Please confirm?")) {
$scope.Message = "You clicked YES.";
} else {
$scope.Message = "You clicked NO.";
}
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" value="Show Confirm" ng-click="ShowConfirm()" />
<br />
<br />
<span ng-bind = "Message"></span>
</div>
</body>
</html>
Screenshot
Demo
Downloads
Download Code