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

      

  • 相关阅读:
    *HDU2473 并查集
    *HDU3172 并查集
    *cf.4 贪心
    *HDU3635 并查集
    *HDU1325 并查集
    *HDU1829 并查集
    Node.js 学习笔记二
    Node.js 学习笔记 一
    AngularJS 学习笔记 一
    MongoDB 基础知识二
  • 原文地址:https://www.cnblogs.com/itman70s/p/ngif.html
Copyright © 2020-2023  润新知