Extending global angular object - good practice?


#1

Hi there!

In an Ionic project we are extending the global angular object like this:

angular
        .module('demo')
        .config(extendAngular);

function extendAngular() {
    angular.isUndefinedOrNull = function (val) {
        return angular.isUndefined(val) || val === null;
    };

    angular.isCordovaSupported = function () {
        return angular.isDefined(window.cordova);
    };
}

By doing so, we can call angular.isUndefinedOrNull() and angular. isCordovaSupported from anywhere within the app.

Is this a good practice? If not, what would be better approaches to accomplish the same?


#2

you should not do that. add a service and implement those functions in the service.
After that you can inject this service in any other component of your module.

angular
        .module('demo')
        .service('helpers', function () {
            this.isUndefinedOrNull = .....
        })
        .controller('testCtrl', function (helpers) {
             // use helpers.isUndefinedOrNull, ....
        });

#3

Thanks @bengtler for your reply. What is the reason why one should not do that? By doing so, one can use those tiny utility functions from anywhere, without having to inject a service everywhere. How would it harm? Don’t really understand the reason behind.


#4

See a lib or a framework as an encapsulated piece of code.
You do not know what will happen there in the future --> how they rename their functions and so on. (or maybe there are functions, properties named like this).

In professional programming you should avoid that, because if work together with other people they will not understand that on the first look. They will see “Hey there is a super fancy function on angular i did not know”. In the next project they want to use it again … and boom", :slight_smile:

And if you are too lazy to inject a service name in the parts of code you need it …


#6

Alright, thanks very much for your detailed answer. Now it’s clear to me why it should be done differently.