Skip to content Skip to sidebar Skip to footer

Extending Angular Global Object In Typescript

I'm using Angularjs and Typescript and I would like to extend the angular object with a custom function like this: angular.executeAfterDigest(function(){...}); How do I go around

Solution 1:

Just tell typescript about it by adding to the interface : https://github.com/borisyankov/DefinitelyTyped/blob/master/angularjs/angular.d.ts#L9

declaremodule ng {
    interface IAngularStatic {
        executeAfterDigest:Function;
    }
}

update

I would prefer not to change the angular.d.ts as it's a third party component

You wouldn't put this in angular.d.ts. You would put this in your globals.d.ts (or vendor.d.ts) to document how you are customizing the vendor libraries (here angular) you are using in your project.

Remember: Interfaces are open ended.

Solution 2:

Updating for current state of things:

basarat's answer didn't work for me and it broke IAngularStatic typing in my app, but adding this to my global.d.ts fixed the custom angular extending function problem:

declarenamespace angular {
    interface IAngularStatic {
        copyData:Function;
    }
}

I derived the declare module ng to declare namespace angular change from Definitely Typed structure linked by basarat: https://github.com/borisyankov/DefinitelyTyped/blob/master/angularjs/angular.d.ts#L9

Solution 3:

Since angular is a singleton instance, you can just do:

angular.executeAfterDigest = function(fn) {
    setTimeout(fn,0);
}

When you call it, it is not guaranteed to execute after a digest. You would have to make sure that it is only called when $scope.$$phase is $digest or $apply. Basically, it will only work when you're in the angular world.

Post a Comment for "Extending Angular Global Object In Typescript"