Angular ng-if and ng-show combination

后端 未结 4 586
不知归路
不知归路 2020-12-31 06:18

Imagine some heavy content that might be rendered on a web page, such as a chart. Angular gives 2 options to toggle the visibility of said content.

ng-show

4条回答
  •  爱一瞬间的悲伤
    2020-12-31 07:02

    You may be interested in a custom directive ng-lazy-show by Alan Colver. It allows combining both ng-if and ng-show:

    The code is small and can easily be added to your project:

    var ngLazyShowDirective = ['$animate', function ($animate) {
    
      return {
        multiElement: true,
        transclude: 'element',
        priority: 600,
        terminal: true,
        restrict: 'A',
        link: function ($scope, $element, $attr, $ctrl, $transclude) {
          var loaded;
          $scope.$watch($attr.ngLazyShow, function ngLazyShowWatchAction(value) {
            if (loaded) {
              $animate[value ? 'removeClass' : 'addClass']($element, 'ng-hide');
            }
            else if (value) {
              loaded = true;
              $transclude(function (clone) {
                clone[clone.length++] = document.createComment(' end ngLazyShow: ' + $attr.ngLazyShow + ' ');
                $animate.enter(clone, $element.parent(), $element);
                $element = clone;
              });
            }
          });
        }
      };
    
    }];
    
    angular.module('yourModule').directive('ngLazyShow', ngLazyShowDirective);
    

提交回复
热议问题