Why and When to Use the Global Object Services in Angularjs?

 

Why and When to Use the Global Object Services in Angularjs?

 

 

 

Why and When to Use the Global Object Services

The main reason that AngularJS includes these services is to make testing easier. I get into testing in Chapter 25, but an important facet of unit testing is the need to isolate a small piece of code and test its behaviour without testing the components it depends on—in essence, creating a focused test. The DOM API exposes functionality through global objects such as document and window. These objects make it hard to isolate code for unit testing without also testing the way that the browser implements its global objects. Using services such as $document allows AngularJS code to be written without directly using the DOM API global objects and allows the use of AngularJS testing services to configure specific test scenarios.

Accessing the Window Object The $window service is simple to use, and declaring a dependency on it gives you an object that is a wrapper around the global window object. AngularJS doesn’t enhance or change the API provided by this global object, and you access the methods that the window object defines as you would if you were working directly with the DOM API. To demonstrate this service—and the others in this category—I have added an HTML file called domApi.html.

 

<!DOCTYPE html>

<html ng-app="DotNetMinds">

<head>

    <title>DOM API Services</title>

    <script src="../Scripts/angular.js"></script>

    <link href="../Content/bootstrap-theme.css" rel="stylesheet" />

    <link href="../Content/bootstrap.css" rel="stylesheet" />

    <script> angular.module("DotNetMinds", [])

     .controller("windowsCtrl", function ($scope, $window) {

         $scope.displayAlert = function (msg) {

             $window.alert(msg);

         }

     });

    </script>

</head>

<body ng-controller="windowsCtrl" class="well">

    <button class="btn btn-primary" ng-click="displayAlert('Clicked!')">Click Me</button>

</body>

</html>

 

Accessing the Document Object 

The $document service is a jqLite object containing the DOM API global window.document object. Since the service is presented via jqLite, you can use it to query the DOM using the methods I described in example.

<!DOCTYPE html>

<html ng-app="DotNetMinds">

<head>

    <title>DOM API Services</title>

    <script src="../Scripts/angular.js"></script>

    <link href="../Content/bootstrap-theme.css" rel="stylesheet" />

    <link href="../Content/bootstrap.css" rel="stylesheet" />

    <script> angular.module("DotNetMinds", [])

     .controller("defaultCtrl", function ($scope, $window, $document)

     { $document.find("button").on("click", function (event) { $window.alert(event.target.innerText); }); });

     </script>

</head>

<body ng-controller="defaultCtrl" class="well">

    <button class="btn btn-primary">Click Me</button>

</body>

</html>

 

Using Intervals and Timeouts:

The $interval and $timeout services provide access to the window.setInterval and window.setTimeout functions, with some enhancements that make it easier to work with AngularJS. Table shows the arguments that are passed to these services.

The Arguments Used with the $interval and $timeout Services 

Argument

Description

fn

A function whose execution will be delayed.

delay

The number of milliseconds before fn will be executed.

count

The number of times that the delay/execute cycle will be repeated ($interval only). The default value is zero, which means there is no limit.

invokeApply

When set to true, which is the default value, fn will be executed within the scope.$apply method.

 

<!DOCTYPE html>

<html ng-app="DotNetMinds">

<head>

    <title>DOM API Services</title>

    <script src="../Scripts/angular.js"></script>

    <link href="../Content/bootstrap-theme.css" rel="stylesheet" />

    <link href="../Content/bootstrap.css" rel="stylesheet" />

    <script>

        angular.module("DotNetMinds", [])

     .controller("intervalCtrl", function ($scope, $interval) {

         $interval(function () {

             $scope.time = new Date().toTimeString();

         }, 2000);

     });

    </script>

</head>

<body ng-controller="intervalCtrl">

    <div class="panel panel-default">

        <h4 class="panel-heading">Time</h4>

        <div class="panel-body"> The time is: {{time}} </div>

    </div>

</body>

</html>

 

I use the $interval service to execute a function that updates a scope variable with the current time every two seconds. I omitted the final two arguments, which means the default values are applied.

Accessing the URL 

The $location service is a wrapper around the location property of the global window object and provides access to the current URL. The $location service operates on the part of the URL following the first # character, which means it can be used for navigation within the current document but not to navigate to new documents. This may seem odd, but you rarely want the user to navigate away from the main document because it unloads your web application and discards your data and state. Consider the following URL, which is typical of an AngularJS application:

<!DOCTYPE html>

<html ng-app=" DotNetMinds ">

<head>

    <title>DOM API Services</title>

    <script src="../Scripts/angular.js"></script>

    <link href="../Content/bootstrap-theme.css" rel="stylesheet" />

    <link href="../Content/bootstrap.css" rel="stylesheet" />

    <script>

 angular.module("DotNetMinds", []) .controller("locationCtrl", function ($scope, $location) {

$scope.$on("$locationChangeSuccess", function (event, newUrl) { $scope.url = "google.com"; });

$scope.setUrl = function (component)

{

    switch (component)

    {

        case "reset": $location.path("");

            $location.hash("");

            $location.search("");

            break;

        case "path": $location.path("/cities/newyork");

            break;

        case "hash": $location.hash("south");

            break;

        case "search": $location.search("select", "restaurants");

            break;

        case "url": $location.url("/cities/london?select=restaurants#south");

            break;

    }

}

});    </script>

</head>

<body ng-controller="locationCtrl">

    <div class="panel panel-default"> 

    <h4 class="panel-heading">URL</h4> 

    <div class="panel-body"> 

        <p>The URL is: {{url}}</p> 

        <div class="btn-group "> 

        <button class="btn btn-primary" ng-click="setUrl('reset')">Reset</button> 

        <button class="btn btn-primary" ng-click="setUrl('path')">Path</button> 

        <button class="btn btn-primary" ng-click="setUrl('hash')">Hash</button> 

        <button class="btn btn-primary" ng-click="setUrl('search')">Search</button> 

        <button class="btn btn-primary" ng-click="setUrl('url')">URL</button> 

        </div> 

        </div>    

    </div>

</body>

</html>

 

 

(Visited 126 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *