Overview

AngularJs is one of the widely used open sources front-end framework because of its good architecture in place, the extensibility, a lot of interesting features and the big community too.

In this short article, we're going to showcase with a simple example why it's sometimes better to use AngularJS's inbuilt global objects and services instead of native ones.

Why using angular wrappers?

AngularJs applications are benefiting from some great functionalities, instead of just using those necessary for frontend architecture as an AngularJs lover I strongly advice to also take advantages of the others global objects and services.

The case to show as an example is the famous setTimeout function of the javascript window object which has its $timeout corresponding service in AngularJs world.

In simple word AngularJs wrappers and services are already built to synchronized with AngularJs application, so can be used without any further tricks.

Timeout case

setTimeout is part of the window object, helpful to execute a function or evaluating an expression one time after a certain delay in milliseconds.

Let's setting up a basic AngularJS application with a controller:

(function (angular) {
    'use strict';

    angular
        .module('myApp', []) // Define our angular app
        .controller('IndexController', IndexController); // We setup the controller

        IndexController.$inject = ['$scope', '$timeout'];

        function IndexController($scope, $timeout) {
            $scope.firstMessage = 'First message';
            $scope.secondMessage = 'Second message';

            // Let's update the first message after 2 seconds
            // Angular $timeout service
            $timeout(function() {
                $scope.firstMessage = 'First message updated';
                alert($scope.firstMessage);
            }, 2000);
            
            // Let's update the second message after 2 seconds
            // Native implementation
            setTimeout(function() {
                $scope.secondMessage = 'Second message updated';
                alert($scope.secondMessage);
            }, 2000);

            // Be aware that if the timeout was called in the second place the digest could be also updated
        }
})(window.angular);

In this example, after 2 seconds the firstMessage will be updated but the secondMessage not, as shown on the following page:

setTimeout:

Here is invoked with two parameters, the function we would like to call and the delay for it to happen.

When we are using it into an AngularJs application we also need to apply the eventual scope changes to the angular digest, because the default timeout runs outside of the AngularJs life-cycle that also means our bi-directional binding will not render the update.

That is why it's needed here to refresh the AngularJs scope with the call of $rootScope.$apply() or $rootScope.$applyAsync().

$apply and $applyAsync serve the same purpose but with a delay difference on the second one.

$timeout:

Almost the same syntax as the previous but there are more parameters here that can be pass to its call.
For example, we can also decide to call it outside of the life cycle:
$timeout(function() {
$scope.firstMessage = 'First message updated';
alert($scope.firstMessage);
}, 2000, false);
Here we see that one more parameter can be added to this service, it's a boolean to say if yes or no we want the apply to follow our function call after 2 seconds.
In simple word, call it with false as the third parameters will call our function outside of AngularJS framework.
Note: By default this third parameter is true.
The documentation stated it clearly here.
 

Others wrappers and utilities functions

There are some others angular wrapper services for corresponding Javascript object that can be interesting to use instead of the native one, sometimes because of the simplicity/syntax or because of the effect as the one just described up there.

Functions

Let's see another example, where the intent is to know if a variable hasn't been declared or has the value undefined.

Here I fill more confident to use:

if(angular.isDefined(variable)) {

}

Instead of:

if(typeof variable != 'undefined') {

}

Others that may be good for you:

  • angular.isDate: to know if a variable is a date
  • angular.isArray: figure out if it's an array
  • angular.copy: make a deep copy an object
  • angular.isObject: test an object type
  • angular.toJson: serialize an object into JSON
  • angular.fromJson: deserialize a JSON string to an object

Others are listed here.

Services

Some AngularJs services:

  • $document: wrapper for the browser window.document object
  • $interval for window.setInterval, the repeated version of setTimeout
  • $http to make remote HTTP call using XMLHttpRequest object or via JSONP
  • $log for logging into the browser's console

More services are available in the documentation.

Conclusion

To resume, in this article we have seen why sometimes it's better to use AngularJs wrappers instead of native implementations while highlighted the timeout case.

The full source code is available over on GitHub.


Orleando Dassi

I'm a Solutions Architect who is constantly learning to better himself while impacting the community by producing technical articles and videos, what describes me the most is my flexibility.

Related Posts

AngularJS

Build a real time app with MEAN2 and socket.io

Build a simple real-time application that you can use as a starter to do what you want with MEAN2(MongoDB, Express, Angular2 & NodeJS), within the project will also be Socket.io, Typescript and Angular-material2. After having worked with Angular2 Read more...

JavaScript

How I Published my First NPM Package in 1h

Open source has been a game-changer for us all, it’s even crucial for software developers. I mean, none of us can say he never used open-sourced projects. Sometimes we feel like we can add our Read more...

Angular

Custom State Management Architecture using RxJS

As a developer, building frontend applications is becoming less difficult using a set of techniques that have been standardized with time, within that jargon, one of these is the State Management System which is a Read more...

Shares