【问题标题】:Jade If Statement Not Working With VariableJade If 语句不适用于变量
【发布时间】:2014-03-13 23:12:45
【问题描述】:

我正在尝试将变量的值与常量字符串进行比较,但我无法让 if 语句正常工作。我在 Jade 中使用 Angular.js。

这是我的代码。

ol
  li(ng-repeat = "notification in notificationData")
    - var typeOfNotification = '{{ notification.typeOfNotification }}'
    p #{ typeOfNotification }
    -if (typeOfNotification == 'like')
      p LIKED
    -else
      p ELSE

这给出了输出

like

ELSE

follow

ELSE

like

ELSE

like

ELSE

follow

ELSE

if 语句永远不会被评估为真,即使上面一行中的p #{ typeOfNotification } 表明在某些情况下变量包含值like。我应该如何更改我的 Jade 代码才能使其正常工作?

谢谢。

【问题讨论】:

    标签: html angularjs pug


    【解决方案1】:

    这里的问题是:Jade 的评估会在 Angular 初始化之前完成。
    所以不能混!

    您是否在服务器端渲染 Jade 模板?还是编译成 JavaScript 并在客户端加载模板?

    对于第一个版本,您不能这样做,对于第二个版本,您需要在使用 Jade 将模板渲染到 DOM 之前初始化 Angular,并可能将上下文传递给 Jade 模板。

    无论如何,如果您将 Jade 中的逻辑提取到您的 Angular 代码中,您就可以解决它。 我对 Angular 不熟悉,所以 ng-call 是我的伪 Angular 指令,它可以调用一个在全局范围内定义和访问的简单函数,并将返回值放在元素节点中:

    script.
      var getNotificationType = function(notification) {
        return notification.typeOfNotification
      }
      var typeIsLike = function(n) {
        var type = getNotificationType(n);
        if (type === 'like') {
          return 'LIKED';
        }
        return 'ELSE';
      }
      var foo = "bar";
    
    
    ol
      li(ng-repeat = "notification in notificationData")
      p(ng-call = "getNotificationType(notification)")
      p(ng-call = "typeIsLike(notification)")
    

    顺便说一句:你可以写 p= typeOfNotification 而不是 p #{ typeOfNotification }
    (如果可以的话;)

    【讨论】:

    • 这很有意义。谢谢!
    【解决方案2】:

    您不能使用从角度到翡翠的变量if,但您可以在翡翠中使用角度ng-if

    ol
      li(ng-repeat = "notification in notificationData")
        p(ng-if= "notification.typeOfNotification == 'like'") LIKED 
        p(ng-if= "notification.typeOfNotification != 'like'") ELSE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2021-09-28
      • 2018-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      相关资源
      最近更新 更多