AngularJS 指令之 ng-if


用途

ng-if 屬性用來控制頁面內元素的添加或移除

 

用法 
 
<label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
Show when checked:
<span ng-if="checked">This is removed when the checkbox is unchecked.</span>

 

工作原理

本以為ng-if和ng-show/ng-hide類似(4行代碼),單純的進行元素的添加刪除,然而ng-if要復雜得多,40多行代碼 。子元素的ng事件,scope處理等。

ng-if 條件為true時,將所在元素的克隆添加到其父元素內,然后處理該元素以及內部所有子元素的ng事件;為false時,將父元素中移除,並且將其scope刪除。

ngif的核心代碼:

var block, childScope, previousElements;
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {

  if (value) {
    if (!childScope) {
      $transclude(function(clone, newScope) {
        childScope = newScope;
        $animate.enter(clone, $element.parent(), $element);
      });
    }
  } else {
    if (previousElements) {
      previousElements.remove();
      previousElements = null;
    }
      $animate.leave(previousElements).then(function() {
        previousElements = null;
      });
  }
});

 

 

 

常見問題

元素不隨着指定的值進行添加或刪除

<div ng-if="{{myValue}}" class="ng-hide"></div>

上述代碼中ng-if 綁定的是{{}}表達式的值對應的字符串,而不是myValue。布爾型對應的是"" 空串 或者 "true" 所以,myValue值變化后,對於ng-if而言,監視的是固定的字符串,沒有變化。也就不會觸發頁面元素的添加或刪除事件。

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM