Javascript 如何在 AngularJS ng-if 语句中使用“>”比较器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33926520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:40:07  来源:igfitidea点击:

How to use ">" comparator in AngularJS ng-if statement

javascripthtmlangularjsangular-ng-if

提问by krhithm

Is it possible to use the 'greater than' comparator in an ng-if in HTML? The problem is that the ">" symbol prematurely closes the HTML tag.

是否可以在 HTML 的 ng-if 中使用“大于”比较器?问题是“>”符号过早地关闭了 HTML 标记。

ex. this: <div ng-if="foo>0" class="bar"> (HTML STUFF) </div>

前任。这个:<div ng-if="foo>0" class="bar"> (HTML STUFF) </div>

is read as: <div ng-if="foo"> (0 class="bar"> HTML STUFF) </div>

读作: <div ng-if="foo"> (0 class="bar"> HTML STUFF) </div>

I ended up getting around this by using ng-if="foo!=0" but I could probably use the less than comparator instead but I was just curious in case I absolutely HAD to use the greater than symbol for some reason. Or would I perhaps have to move this logic somewhere else like in my controller instead of in my view?

我最终通过使用 ng-if="foo!=0" 解决了这个问题,但我可能可以使用小于比较器,但我只是好奇,以防我出于某种原因绝对必须使用大于号。或者我是否可能必须将此逻辑移动到其他地方,例如在我的控制器中而不是在我的视图中?

EDIT 1So it definitely seems like the comparator itself isn't the problem and something else is going on in my code. Oddly, when I have spaces before and after the comparator it works but without spaces it doesn't. I'm also using angular 1.3.15 if that means anything.

编辑 1所以看起来比较器本身似乎不是问题,我的代码中还有其他问题。奇怪的是,当我在比较器前后有空格时,它可以工作,但没有空格就不行。如果这意味着什么,我也使用 angular 1.3.15。

<div class="paginate" ng-if="list.total > 0">works

<div class="paginate" ng-if="list.total > 0">作品

<div class="paginate" ng-if="list.total>0">does not work

<div class="paginate" ng-if="list.total>0">不起作用

回答by user1532669

This is an example of using the >symbol. This works fine.

这是使用>符号的示例。这工作正常。

<div ng-if="myvariable.length > 2">

</div>

回答by Artem K.

I recommend creating a method on the scope and abstracting the logic of the condition. The business rules may expand and change. With a separate method you don't need to alter the template.

我建议在范围上创建一个方法并抽象条件的逻辑。业务规则可能会扩展和更改。使用单独的方法,您无需更改模板。

// in controller
$scope.isValidFoo = function () {
    return $scope.foo > 0;
}

// in template
<div ng-if="isValidFoo()">...</div>