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 :)
Gaurav Kumar AroraPosted Dec 12, 2014, 2:50 PM
Jaganathan Bantheswaran - greatly elaborated, I found this on the same way. I did it earlier but wasn't able to get it on paper :)
Gaurav Kumar AroraPosted Nov 23, 2014, 9:42 AM
Jaganathan Bantheswaran - I am completely unaware from this. It never run for me without ng-app :)
Jaganathan BantheswaranPosted Nov 21, 2014, 12:45 AM
Nice one Gaurav. Sumit & Gaurav, AngularJS will work perfectly without using ng-app :)
Guest UserPosted Nov 20, 2014, 8:11 AM
:) that's why i was wondering I never encountered case where it'll work without ng-app
Guest UserPosted Nov 20, 2014, 7:47 AM
I never tried AngularJS without 'ng-app', so will it work, if yes then why? pls answer
Guest UserPosted Nov 20, 2014, 7:45 AM
Good ex Gaurav Arora. I like this interpretation angularAlert => { $window.alert(angularAlert); };