AngularJS:三元运算符条件检查中的函数调用

Posted

技术标签:

【中文标题】AngularJS:三元运算符条件检查中的函数调用【英文标题】:AngularJS: Function call in ternary operator conditional check 【发布时间】:2016-11-17 08:46:39 【问题描述】:

我的 HAML 文件:

%pipes-autocomplete:model =>"filter.value",:option => "validate_option(filter)" ? "dependant(filter)" : "filter.option"

我的咖啡脚本:

  $scope.validate_option =(filter)->
     console.log "called validate_option"
     if filter.hasOwnProperty('option') && filter.option.indexOf('dependant') > -1
       return true
     else
      return false
  $scope.dependant =(cal)->
    return "choosed"

在三元运算符中,我试图调用在我的角度控制器中定义的 validate_option 函数。但该函数没有被调用。有人可以帮我解决这个问题吗?

【问题讨论】:

正如您现在所说的,三元运算符将认为字符串为真(只是因为它不是空的)。尝试使用"validate_option(filter) ? dependant(filter) : filter.option"(全部在一个字符串中),以便将三元运算符的执行推迟到评估字符串时。 @trincot 非常感谢。它工作正常。我是角度的新手。你的解释消除了我的疑虑。 【参考方案1】:

正如您在问题中所说,三元运算符会将字符串"validate_option(filter)" 视为true(只是因为它不是空的)。

而是将三元运算符放在字符串中:

"validate_option(filter) ? dependant(filter) : filter.option"

这样,您可以将三元运算符的执行推迟到实际计算字符串时。

【讨论】:

以上是关于AngularJS:三元运算符条件检查中的函数调用的主要内容,如果未能解决你的问题,请参考以下文章

三元表达式是啥?

如何在 JSX 的三元运算符中调用两个函数?

三元条件下的多个 OR 运算符,

如何将变量传递给angularjs中的三元条件?

三元运算符,如果为真则返回检查条件的快捷方式?

在 AngularJS 的三元运算符中使用过滤器