使用 AngularJS 创建渲染条件 [英] Make a render condition with AngularJS

查看:33
本文介绍了使用 AngularJS 创建渲染条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在 AngularJS 中创建一个 view 条件,它会根据条件显示或隐藏 dom 元素:

<div ng-show="{{isTrue}}">一些内容</div>

但是我如何创建一个 render 条件来决定是否渲染 div?

解决方案

针对 angularjs 1.1.5 及以上用户的更新(1.0.7 不支持):

<块引用>

相关提交:https://github.com/angular/angular.js/commit/2f96fbd17577685bc013a4f7ced06664af253944"

Angular 现在有一个条件渲染指令:ngIf.

用法:

<块引用>

注意,当使用 ng 删除元素时,如果它的作用域被销毁,并且在元素恢复时创建一个新的作用域

文档:directive-ngIf

对于旧版 angularjs 用户:

ngShow 指令有条件地隐藏/显示元素.这将在新的稳定版本之一中进行更改,现在可以在 unstable 版本中使用,与 1.1.5 一样.

如果你想有条件地添加/删除DOM上的项目,可以使用ngSwitch.

<div ng-switch-when="true">你好!</div>

实际上,该指令是为处理超过 1 个案例而创建的,但您也可以这样使用它.有关更复杂用法的示例,请参阅答案.>

I know how to make a view condition in AngularJS, that will display or hide dom element dependent on the condition:

<div ng-show="{{isTrue}}">Some content</div>

but how do I create a render condition that determines whether to render or not the div?

解决方案

Update for angularjs 1.1.5 and above users (not supported in 1.0.7):

Related commit: https://github.com/angular/angular.js/commit/2f96fbd17577685bc013a4f7ced06664af253944

Angular now have a conditional rendering directive: ngIf.

Usage:

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

Note that when an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored

Documentation: directive-ngIf

For legacy angularjs users:

ngShow directive conditionally hides/shows the element. This is going to be changed in one of the new stable releases, it is now available in the unstable release as with 1.1.5.

If you want to conditionally add/remove items on DOM, use can use ngSwitch.

<div ng-switch="showMe">
    <div ng-switch-when="true">Hello!</div>
</div>

Actually, this directive has been created for handling cases for more than 1, but you can use it that way too. See this answer for examples of more sophisticated usages.

这篇关于使用 AngularJS 创建渲染条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆