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


i wanted introduce enum controller logic type safety, example created 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 example page have 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>    </div> </div>  <script type="text/ng-template" id="login">     <button ng-click="login()">login</button> </script>  <script type="text/ng-template" id="logout">     <button ng-click="logout()">logout</button> </script> 

but ng-switch-when not want work. works if substitute values in ng-swith-when manually integers, example 1,2.

here fiddles demonstrate this:

http://jsfiddle.net/jnxye/3/

http://jsfiddle.net/4jg7m/2/

now, can see, first 1 not work, , second 1 works - meaning changes button when button clicked.

the problem think var stateenum = object.freeze({"login":1, "logout":2}).

is possible use enum in html ng-switch-when work (as in second fiddle)?

i think create service have enums:

angular.module('enums', []).    factory('enum', [ function () {        var service = {         freeze: {login:1, logout:2 },           somethingelse: {abc:1,def:2}       };       return service;      }]); 

your app definition this:

var app = angular.module('myapp', ['enums']); 

then controllers inject them when need them:

function logincheckctrl($scope, enum) {     if (1==enum.freeze.login) // example     if (1==enum.somethingelse.abc)  // example 

services singletons give set of enums define.

as ngswitch when directive, believe requires string (please correct me if i'm wrong). couple references:

https://groups.google.com/forum/?fromgroups#!topic/angular/eh4w0y93zaa https://github.com/angular/angular.js/blob/master/src/ng/directive/ngswitch.js#l171

an alternate way achieve want use ng-show/ng-hide

<div ng-include="'login'" ng-show='stateenum.login==logindata' ...> 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -