9

In Typescript I created an enum like this:

enum Action { None = 0, Registering = 1, Authenticating = 2 };

In my controller I set a property called action like this:

class AuthService implements IAuthService {

    action: number;

    constructor(
        private $state,
        private userService,
        private utilityService: IUtilityService
        ) {

        this.action = Action.None;

    }

    doRegister() => {
       this.action = Action.Registering;
    }

This works good but how can I use the enum in my HTML. Is that possible? What I would like to do is to use it in some place like this:

<span ng-class="{'fa-spin fa-spinner': app.authService.authenticating }">

Without the need to create different variables for:

app.authService.authenticating
app.authService.registering
...
etc

1 Answer 1

11

You can put that on the $rootScope e.g.

mainmodule.run([
    '$rootScope'
], function ($rootScope){

    // put it on $rootScope
    $rootScope.Action = Action;
});

And since every $scope inherits from it it is on each scope and you can just do Action.foo etc.

Note: For directives with an isolate scope you need to do $root.Action.foo. Just Action would not work as it intentionally breaks the prototype chain.

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

3 Comments

I've been doing some checking into the use of constants also. Do you think it's easier to use the app.constant( or use a Typescript solution?
Can you show me how I would inject $rootScope into the controller? Do I inject $rootScope or just $scope?
Both. But you don't need to. Use enums like any other ts utility function that doesn't need access to angular

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.