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

      

  • 相关阅读:
    Git
    Entropy, relative entropy and mutual information
    2021.5.3 团队冲刺第六天
    2021.5.2 团队冲刺第五天
    2021.5.1 团队冲刺第四天
    2021.4.30 团队冲刺第三天
    2021.4.29 团队冲刺第二天
    2021.4.28 团队冲刺第一天
    2021.4.27
    2021.4.26
  • 原文地址:https://www.cnblogs.com/itman70s/p/ngif.html
Copyright © 2011-2022 走看看