javascript - 如何与 ng-switch 中的全局变量进行比较

标签 javascript angularjs ng-switch rootscope

我正在使用 AngularJS $rootScope 对象来公开一些需要 Controller 和 View 都可以访问的全局常量:

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

app.run(function ($rootScope) {
    $rootScope.myConstant = 2;
});

当我尝试在 View 中呈现全局值时,它可以正常工作:

{{myConstant}}

同样,如果我在 ng-if 条件中引用全局值,它也有效:

<span ng-if="someValue == myConstant">Conditional content</span>.

但是,当尝试在 ng-switch block 中使用相同的值进行比较时,它永远不会计算为真。 This JSFiddle展示了我试图让这个工作。我还尝试将常量值显式引用为 $rootScope 的成员和表达式(在双花括号内),但没有任何效果。

知道我做错了什么吗?

谢谢,

蒂姆

最佳答案

而不是尝试设置 ng-switch-when , 你可以自定义 ng-switch-on myConstant时为了产生特定值的表达式等于 item.value :

<span ng-switch on="{true:'const', false: item.value}[myConstant == item.value]">
    <span ng-switch-when="const">
        <span class="blue">{{item.name}}</span> (emphasis applied by ng-switch) 
    </span>
    <span ng-switch-when="4">
        <span class="red">{{item.name}}</span> (emphasis applied by ng-switch) 
    </span>
    <span ng-switch-default>
        {{item.name}}
    </span>
</span>

Working example .

关于javascript - 如何与 ng-switch 中的全局变量进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18594697/

相关文章:

angularjs - 当 AngularJS 作为前端时,Express 中的 session 未定义

ng-switch 中的 AngularJS $index

javascript - 语法错误 : import not found: default when defining a js class

javascript - 手动设置 react 表单内表单数组元素的值

javascript - AngularJS $anchorScroll yOffset 在子元素中

AngularJS 路由,从 URL 中删除 #

javascript - 如何根据空格和限制拆分字符串?

javascript - 移动浏览器的样式下拉列表

javascript - angularjs ng-switch-when 输入字段的值

angularjs - ng-switch-when 与 ng-repeat