Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
How do I show Alert in AngularJS?
WhatsApp
Gaurav Kumar Arora
4y
124.3
k
0
2
25
Blog
Alert is a part of 'window' (an object of a Browser), which is a global variable.
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 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:
angular.module("angularAlert", [])
.controller("myController", [
"$scope", "$window", ($scope, $window) =
>
{
$
scope.angularAlert
=
"This is an AngularJS alert!"
;
$
scope.clickMe
=
angularAlert
=
>
{
$window.alert(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
>
</
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 :)
How do I show Alert in AngularJs
Up Next
Create an Alert Message from Controller View Using JavaScript Alert MessageBox
Ebook Download
View all
Frontend Developer Interview Questions and Answers
Read by 950 people
Download Now!
Learn
View all
Membership not found