javascript Angular.js 和 ng-switch-when - 模拟枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16627860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:25:16  来源:igfitidea点击:

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

javascriptangularjsenums

提问by Andna

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>
   </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-whendoes not want to work. It only works if I substitute values in ng-swith-whenmanually with integers, for example 1,2.

ng-switch-when不想工作。它仅在我ng-swith-when用整数手动替换值时才有效,例如 1,2。

Here are fiddles to demonstrate this:

这里有小提琴来证明这一点:

http://jsfiddle.net/jNxyE/3/

http://jsfiddle.net/jNxyE/3/

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

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

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}).

我认为的问题是这个var StateEnum = Object.freeze({"login":1, "logout":2})

Is is possible to use my enum in my html so ng-switch-whenwill work properly (as in second fiddle)?

是否可以在我的 html 中使用我的枚举以便ng-switch-when正常工作(如第二小提琴)?

回答by lucuma

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 (1==Enum.somethingelse.abc)  // 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:

至于 ngSwitch when 指令,我相信它需要一个字符串(如果我错了,请纠正我)。几个参考:

https://groups.google.com/forum/?fromgroups#!topic/angular/EH4W0y93ZAAhttps://github.com/angular/angular.js/blob/master/src/ng/directive/ngSwitch.js#L171

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 to achieve what you want would be to use ng-show/ng-hide

实现您想要的另一种方法是使用ng-show/ng-hide

<div ng-include="'login'" ng-show='stateEnum.login==loginData' ...>

回答by RyanNerd

Here's a real world example of how to emulate enums using Angular with standard JavaScript and BootStrap. This is to display details of an order also called a ticket.

这是一个真实世界的示例,说明如何使用 Angular 和标准 JavaScript 和 BootStrap 模拟枚举。这是为了显示订单的详细信息,也称为票证。

Define your enums as Angular constants:

将您的枚举定义为 Angular 常量:

 app = angular.module("MyApp", [])
.constant('ENUMS',
    {
        TicketStatusText: { 0: 'Open', 3: 'Ready', 1: 'Closed', 2: 'Overring' },
        TicketStatus: {Open:0, Ready:3, Closed:1, Overring:2}
    }
    )

Your controller code should look something like this:

您的控制器代码应如下所示:

app.controller("TicketsController", function ($scope, $http, ENUMS) {
$scope.enums = ENUMS;

Your HTML with BootStrap should look something like this:

带有 BootStrap 的 HTML 应如下所示:

<table>
<tr ng-repeat="ticket in tickets" ng-class="{danger:ticket.CurrentStatus==enums.TicketStatus.Overring}">
<td>
<strong>{{ticket.TransNumber}}</strong>
</td>
<td>
{{enums.TicketStatusText[ticket.CurrentStatus]}}
</td>

Notice in ng-class in combination with BootStrap we compare the current status of the ticket model to enums.TicketStatusText.Overring; this will change the color of the row for any tickets that have an Overring status(2).

请注意,在 ng-class 与 BootStrap 结合使用时,我们将票证模型的当前状态与 enums.TicketStatusText.Overring 进行比较;这将更改任何具有 Overring 状态 (2) 的工单的行颜色。

Also in one of the columns we want to display the ticket status as a string and not as an integer. So this is used: {{enums.TicketStatusText[ticket.CurrentStatus]}}

同样在其中一列中,我们希望将工单状态显示为字符串而不是整数。所以使用:{{enums.TicketStatusText[ticket.CurrentStatus]}}

回答by scalaGirl

Have you looked at this answer on stackoverflow?: Ways to enum

你有没有在 stackoverflow 上看过这个答案?: 枚举的方法

Best answer is from 2008, so look at the newer/latest posts for clues. As I read them, you can get the answer as any primitive you need but I haven't tested this yet. Can anyone suggest a best answer to use with Angular from this post?

最佳答案来自 2008 年,因此请查看较新/最新的帖子以获取线索。当我阅读它们时,您可以根据需要的任何原语获得答案,但我尚未对此进行测试。任何人都可以从这篇文章中提出与 Angular 一起使用的最佳答案吗?

回答by kba

I would suggest using angular.Module.constant. For instance:

我建议使用angular.Module.constant. 例如:

var app = angular.module('app', []);
app.constant('Weekdays', {
    Monday: 1,
    Tuesday: 2,
    Wednesday: 3,
    Thursday: 4,
    Friday: 5,
    Saturday: 6,
    Sunday: 7
});
app.controller('TestController', function(Weekdays) {
    this.weekday = Weekdays.Monday;
});

回答by den baas

I have declared some enums in a seperate file called Enums. (I made this withTypeScript) In the controller of the angular app I have something like this:

我在一个名为 Enums 的单独文件中声明了一些枚举。(我用TypeScript 做了这个)在angular 应用程序的控制器中,我有这样的东西:

var app = angular.module("Sample", ["ngAnimate"])
app.controller("Messages", function ($scope, $sce, $interval, $log, $http) {
    $scope.enums = Enums;
};

The enums in the other file are in a var called Enums.

另一个文件中的枚举位于名为 Enums 的 var 中。

Now you can use this, and even be more creative:

现在你可以使用它,甚至更有创意:

ng-show="anotherVAr == enums.enumOne.VALUE"

回答by Sameera R.

Service

服务

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

app.factory('Enum', function () {
          return {
            Action: {login:1, logout:2 },
            Status: {open:1, close:2}
          };
        });

Controller

控制器

app.controller('TestController', function($scope, Enum) {
    $scope.x = Enum.Action.logout;
    $scope.y= Enum.Status.close;
});