3

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 and do this? I suspect I need to extend IAngularStatic somehow or can I use something like angular.prototype? (I'm not very experienced with extending javascript object to start with).

Maybe it's more proper to create an "angularHelperService" that get injected instead.

3 Answers 3

3

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

declare module 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.

Sign up to request clarification or add additional context in comments.

1 Comment

I would prefer not to change the angular.d.ts as it's a third party component. But it might not be able to do it in any other way?
1

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:

declare namespace 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

Comments

0

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.

2 Comments

As I'm using Typescript I get a compilation error if I try to "declare" an undefined function like that.
sorry, I don't know typescript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.