Showing alert in AngularJs

Alert is a part of ‘window’ (an object of a Browser), which is a global variable. In this blog entry we will discuss how to show alert in angularjs.

In Javascript we can use simply

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 overridden 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. Here is snippet:

angular.module("angularAlert", [])    
    .controller("myController", [    
        "$scope", "$window", ($scope, $window) => {    
            $scope.angularAlert = "This is an AngularJS alert!";    
            $scope.clickMe = angularAlert => {    

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:

<div ng-controller="myController">    
  <input type="text" ng-model="angularAlert" />    
  <button ng-click="clickMe(angularAlert)">Click Me</button>    

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 ?
To know the answer refer to: Initializing angularjs

Enjoy coding 🙂

Leave A Reply