且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

之间有什么区别NG-IF和NG-显示/ NG隐藏

更新时间:2021-12-02 04:01:22

ngIf 指令的删除或重新创建基于一个前pression一个DOM树的一部分。如果分配给 ngIf 除权pression计算结果为假值,则该元素从DOM中移除,否则元素的克隆重新插入DOM。

ngIf

The ngIf directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.

<!-- when $scope.myValue is truthy (element is restored) -->
<div ng-if="1"></div>

<!-- when $scope.myValue is falsy (element is removed) -->
<div ng-if="0"></div>

当一个元素被移除使用 ngIf 其范围被破坏,恢复的元素时创建一个新的范围。在 ngIf 创建范围使用原型继承其父继承范围

When an element is removed using ngIf its scope is destroyed and a new scope is created when the element is restored. The scope created within ngIf inherits from its parent scope using prototypal inheritance.

如果 ngModel 是在 ngIf 用于绑定到一个JavaScript原始父范围定义,任何修改作出到子范围内的变量将不会在父范围影响的值,例如

If ngModel is used within ngIf to bind to a JavaScript primitive defined in the parent scope, any modifications made to the variable within the child scope will not affect the value in the parent scope, e.g.

<input type="text" ng-model="data">
<div ng-if="true">
    <input type="text" ng-model="data">
</div>        

要解决这种情况,并从孩子域内更新父范围的模型,使用对象:

To get around this situation and update the model in the parent scope from inside the child scope, use an object:

<input type="text" ng-model="data.input">
<div ng-if="true">
    <input type="text" ng-model="data.input">
</div>

或者 $父变量引用父范围对象:

<input type="text" ng-model="data">
<div ng-if="true">
    <input type="text" ng-model="$parent.data">
</div>

ngShow

ngShow 指令的显示或隐藏的基础上提供给前任pression给定的HTML元素 ngShow 属性。元素显示或到元素删除或添加 NG-隐藏 CSS类隐藏。在 .ng隐藏 CSS类是在AngularJS pdefined $ P $,并设置显示风格为none(使用!重要标志)。

ngShow

The ngShow directive shows or hides the given HTML element based on the expression provided to the ngShow attribute. The element is shown or hidden by removing or adding the ng-hide CSS class onto the element. The .ng-hide CSS class is predefined in AngularJS and sets the display style to none (using an !important flag).

<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="1"></div>

<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="0" class="ng-hide"></div>

在该 ngShow 前pression计算结果为那么 NG-隐藏 CSS类添加到使其成为隐藏的元素上的属性。当真正 NG-隐藏 CSS类是从元素中删除导致的元素不出现隐藏。

When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute on the element causing it to become hidden. When true, the ng-hide CSS class is removed from the element causing the element not to appear hidden.