zoukankan      html  css  js  c++  java
  • 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而言,监视的是固定的字符串,没有变化。也就不会触发页面元素的添加或删除事件。

      

  • 相关阅读:
    CodeForces 450
    CodeForces 400
    CodeForces 1
    [HDU POJ] 逆序数
    [HDU 1166] 敌兵布阵
    [转] 树状数组学习
    关于1月4日到1月7日
    [HDU 1565+1569] 方格取数
    [POJ 1459] Power Network
    [转] 网络流算法--Ford-Fulkerson方法及其多种实现
  • 原文地址:https://www.cnblogs.com/itman70s/p/ngif.html
Copyright © 2011-2022 走看看