【问题标题】:Angular ng-if isn't hiding if the value is true如果值为 true,Angular ng-if 不会隐藏
【发布时间】:2015-12-23 11:17:35
【问题描述】:

我试图理解为什么 ng-if 没有显示正确的内容。

<div ng-if="user.premium">
     <p>If user.premium is true show this content</p>
</div>
<div ng-if="!user.premium">
     <p>If user.premium is false show this content</p>
</div>

这似乎是我期望它工作的方式。我在 user.premium 上做了一个 console.log,它返回了以下数据。

premium: false; 

在这种情况下,我认为要显示的内容是虚假内容。

在这种情况下,我希望只显示真实的内容。

premium: true;

但是,无论是真还是假,我的 DOM 中都显示了真实的内容。

如果属性为真或假,我将如何显示正确的内容。

【问题讨论】:

  • 你确定 'true' 和 'false' 是布尔值而不是字符串吗?
  • 感谢您的评论,它们是 100% 布尔值
  • 但是console.log(user.premium) 会返回什么?
  • 如果你控制台日志user.premium你得到premium: truetrue?抱歉只是澄清一下:)

标签: javascript angularjs


【解决方案1】:

试试这个解决方案..

确保“用户”,它是您控制器中的对象。像这样..

$scope.user = {};
$scope.user.premium = false; //default value

如果您可以为“$scope.user.premium”分配任何值

$scope.user.premium = true; // Or any other value 

肯定会成功的……

<div ng-if="user.premium">
    <p>If user.premium is true show this content</p>
</div>
<div ng-if="!user.premium">
     <p>If user.premium is false show this content</p>
</div>

【讨论】:

    【解决方案2】:

    在某些情况下会导致此错误。我试着说两句:

    • 您可能需要手动$apply 将范围更改为 false 后。当您在不调用 $apply 的包装器中更改范围内的值时,就会发生这种情况。
    • 您可以使用变量作用域,但在 $rooScope 或子作用域中有同名变量。

    【讨论】:

      【解决方案3】:

      如果您使用 As 控制器(MainController as mainCtrl)。你应该使用 像这样

      <div ng-if="mainCtrl.user.premium">
           <p>If user.premium is true show this content</p>
      </div>
      <div ng-if="!mainCtrl.user.premium">
           <p>If user.premium is false show this content</p>
      </div>
      

      【讨论】:

        【解决方案4】:

        我一直是个彻头彻尾的笨蛋,忘记将值添加到我的范围内..

        答案是将scope.user = user; 添加到我的控制器中。是的,没有美元,因为我们的设置很奇怪。

        为了正确设置,您应该使用美元。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-31
          相关资源
          最近更新 更多