How do I show Alert in AngularJS?

Alert is a part of 'window' (an object of a Browser), which is a global variable.
 
In Javascript we can use simply
  1. alert('Javascript Alert!');  
But, it could create issues of conflicting while using in AngularJS (as it is a Global variable). So, we can't use directly 'window' to show alert in AngularJS.
 
To resolve the same we should use '$window' so, it would be overriden during other operations viz. testing or mocking.
 
Lets take an example, where we need to show an alert message as per input provided by user (with some default inout). Here is snippet:
  1. angular.module("angularAlert", [])    
  2.     .controller("myController", [    
  3.         "$scope", "$window", ($scope, $window) => {    
  4.             $scope.angularAlert = "This is an AngularJS alert!";    
  5.             $scope.clickMe = angularAlert => {    
  6.                 $window.alert(angularAlert);    
  7.             };    
  8.         }    
  9.     ]);  
In above, we just created an angular module 'angularAlert' and named controller 'myController' here we are just using angular service '$window', which give us the ability to interact with browser's window.
 
Lets create an html page so, we can play with angularJS alert:
  1. <div ng-controller="myController">    
  2.   <input type="text" ng-model="angularAlert" />    
  3.   <button ng-click="clickMe(angularAlert)">Click Me</button>    
  4. </div>   
Take a look into above code, we just mark our 'div' with controller 'myController' - this is doing the things:
  • Provides a text in 'angularAlert'
  • Provides a function 'clickMe' - which invokes the entered or default text in window alert.
Can you think why we did not use 'ng-app' in above ?
 
Enjoy coding :)