简体   繁体   English

如何在ng-if中添加自定义条件?

[英]How do I add a custom condition in ng-if?

I have a pre-evaluated conditional statement to be used inside my ng-if. 我在ng-if中使用了预先评估的条件语句。 Something like this, in my angular code: 在我的角度代码中是这样的:

scope.condition = "item.chosen == true";         ---(1)

I need to use this condition in my ng-if condition, something like this: 我需要在ng-if条件中使用此条件,如下所示:

<div ng-if="{{condition}}"></div>                ---(2)

Which would ideally be evaluated as 理想情况下,应将其评估为

<div ng-if="item.chosen == true"></div>          ---(3)

This of course doesn't work. 这当然是行不通的。 Just to clarify, I cannot directly use the code in 3 because as I mentioned the scope.condition variable is pre-evaluated and I can't be sure what the string value might be, except that it will be a valid conditional statement. 为了澄清起见,我不能直接使用3中的代码,因为正如我提到的scope.condition变量是预先评估的,并且我不能确定字符串值可能是什么,除了它将是一个有效的条件语句。

How do I achieve this? 我该如何实现?

EDIT 1: 编辑1:

Further clarification, the condition variable need not necessarily be item.chosen == true . 进一步说明,条件变量不必一定是item.chosen == true It could also be something like item.count > limit or item.available == false . 也可能是item.count> limititem.available == false之类的东西 Basically there is no way to know for sure what the condition will be, just that it will always be a valid conditional statement in string format. 基本上,没有办法确定条件将是什么,只是它始终是字符串格式的有效条件语句。

You have to store it like 你必须像这样存储

scope.condition = item.chosen;

and then use it like 然后像

<div ng-if="condition"></div>

it will be evaluated like 它将像

<div ng-if="true"></div>

你可以做

<div ng-if="condition"></div> 

You can try with this 你可以尝试一下

<div ng-if="$eval(condition)"></div>

or 要么

//view
<div ng-if="condition"></div>

//controller
$scope.item.chosen = false;
$scope.condition = $scope.$eval('item.chose == true')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM