Andna Andna - 1 year ago 502
AngularJS Question

Angular.js and ng-switch-when - emulating enum

I wanted to introduce some enum to my controller logic for some type safety, so for example I created something like this:

var app = angular.module('myApp', []);
var StateEnum = Object.freeze({"login":1, "logout":2})
function LoginCheckCtrl($scope) {
$scope.stateEnum = StateEnum
$scope.loginData = StateEnum.login
$scope.login = function() {
console.log($scope.loginData ? 'logged in' : 'not logged in');
$scope.loginData = StateEnum.logout;
$scope.logout = function() {
console.log($scope.loginData ? 'logged in' : 'not logged in');
$scope.loginData = StateEnum.login;

and in my example page I would have something like this:

<div ng-controller="LoginCheckCtrl">
<div ng-switch on="loginData">
<div ng-switch-when="stateEnum.login" ng-include="'login'"></div>
<div ng-switch-when="stateEnum.logout" ng-include="'logout'"></div>

<script type="text/ng-template" id="login">
<button ng-click="login()">Login</button>

<script type="text/ng-template" id="logout">
<button ng-click="logout()">Logout</button>

does not want to work. It only works if I substitute values in
manually with integers, for example 1,2.

Here are fiddles to demonstrate this:

now, as you can see, the first one clearly does not work, and second one works - meaning it changes button when button is clicked.

The problem I think is this
var StateEnum = Object.freeze({"login":1, "logout":2})

Is is possible to use my enum in my html so
will work properly (as in second fiddle)?

Answer Source

I think I would create a service that could have all your enums:

angular.module('Enums', []).
   factory('Enum', [ function () {

      var service = {
        freeze: {login:1, logout:2 },
          somethingelse: {abc:1,def:2}

     return service;


Your app definition would be like this:

var app = angular.module('myApp', ['Enums']);

Then your controllers you could inject them when you need them:

function LoginCheckCtrl($scope, Enum) {
    if (1==Enum.freeze.login) // as an example
    if (  // another example

Services are singletons so this effectively will give you a set of enums you could define.

As for the ngSwitch when directive, I believe it requires a string (please correct me if I'm wrong). A couple references:!topic/angular/EH4W0y93ZAA

An alternate way to achieve what you want would be to use ng-show/ng-hide

<div ng-include="'login'" ng-show='stateEnum.login==loginData' ...>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download