Menu

$window Service In Angular Js

AngularJs includes $window service which refers to the browser window object.

In the JavaScript, window is a global object which includes many built-in methods like alert(), prompt() etc.

The $window service is a wrapper around window object, so that it will be easy to override, remove or mocked for testing. It is recommended to use $window service in AngularJS instead of global window object directly.

 

 

 

 
Example: $window
DOCTYPE html>
<html>
<head>
    <script src="~/Scripts/angular.js">script>
head>
<body ng-app="myApp" ng-controller="myController">
    <button ng-click="DisplayAlert('Hello World!')">Display Alertbutton>
    <button ng-click="DisplayPrompt()">Display Promptbutton>
    <script>
        var myApp = angular.module('myApp', []);

        myApp.controller("myController", function ($scope, $window) {

            $scope.DisplayAlert = function (message) {
                $window.alert(message);
            }

            $scope.DisplayPrompt = function () {
                var name = $window.prompt('Enter Your Name');
                
                $window.alert('Hello ' + name);
            }

        });
    script>
body>
<html>
585
Search

Ads