【问题标题】:How do I display text in view with respect to a boolean variable in the $scope in angularjs?如何在 angularjs 的 $scope 中显示关于布尔变量的文本?
【发布时间】:2013-03-03 08:03:00
【问题描述】:

假设我在 $scope 中有一个变量:

$scope.smsProfile.Active

可以是真或假,我想在屏幕上显示一个关于它的值的文本。例如,如果为真则显示“配置文件处于活动状态”,如果为假则显示“配置文件未激活”。我该怎么做?

我试过这样:

{{true:'Profile active', false:'Profile not active'}[$scope.smsProfile.Active]}

但它不起作用。

【问题讨论】:

    标签: binding angularjs


    【解决方案1】:

    使用 ng-hide 和/或 ng-show 指令:

    <span ng-show="smsProfile.Active">Profile active</span>
    <span ng-hide="smsProfile.Active">Profile not active</span>
    

    【讨论】:

      【解决方案2】:

      在控制器中添加方法:

      $scope.smsProfile= {
              Active: true,
              statusText: function () {
                  return $scope.foo.Active ? 'active' : 'not active';
              }
          }
      

      然后在表达式或ng-bind中输出方法

      <span>Profile is {{smsProfile.statusText()}}</span>
      

      演示:http://jsfiddle.net/zpfq4/

      【讨论】:

      • 不写别的函数就没有办法了吗?
      • 可能...但表达式指南文档声明如下:无控制流语句您不能在表达式中编写控制流语句。这背后的原因是 Angular 哲学的核心,即应用程序逻辑应该在控制器中,而不是在视图中。如果您需要条件、循环或从视图表达式中抛出,请改为委托给 JavaScript 方法。 docs.angularjs.org/guide/expression
      • 另一种选择可能是使用ng-switch
      【解决方案3】:

      虽然这有点旧,但我想为任何最终来到这里的人提供参考:

      How do I display text in view with respect to a boolean variable in the $scope in angularjs?

      下面是另一个示例,使用三元运算符遵循上述帖子的逻辑。此示例基于带有切换按钮的复选框列表,用于选择全部或不选择。如果全部被选中(长度相同),那么选项文本将变为全选。

      {{ (selected.length === options.length) ? 'Select None' : 'Select All'}}
      

      按照这个逻辑,上面也可以这样写:

      {{ (selected.length !== options.length) ? 'Select All' : 'Select None'}}
      

      有关这方面的更多信息,请参阅以下来自 Mozilla 的文章:

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

      【讨论】:

        猜你喜欢
        • 2013-06-06
        • 1970-01-01
        • 1970-01-01
        • 2015-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多