2014-11-03 134 views
3

我在Angular应用中使用了选项卡,当用户需要时,使用ngIf来延迟加载指令和控件。问题是,如果用户浏览它们,我不想重新创建选项卡,并且考虑到这一点,我使用这个特技来初始化该选项卡,并在用户需要时显示它:ngIf使用角度

<button ng-click="tab.show=!tab.show">Toggle tab</div> 

<div ng-if="tab.show || tab.initialized" ng-show="tab.show" ng-init="tab.initialized=true"> 
tab content 
</div> 

我想实现的是使用自定义指令实现此行为,如ng-if-once="tab.show",如果可能的话重用核心ngIf和ngShow指令。有任何想法吗?

编辑

这是我暂时的解决方案,但ngIf保持一个truthy值设置后的工作:

app.directive('ngIfOnce', ['ngIfDirective', 'ngShowDirective', function (ngIfDirective, ngShowDirective) { 
var ngIf = ngIfDirective[0]; 
var ngShow = ngShowDirective[0]; 

return { 
    transclude: ngIf.transclude, 
    priority: ngIf.priority, 
    terminal: ngIf.terminal, 
    restrict: ngIf.restrict, 
    link: function ($scope, $element, $attr) { 
     $attr.ngIf = $attr.ngShow = $attr['ngIfOnce']; 

     var unregisterWatcher = $scope.$watch($attr.ngIf, function (newVal) { 
      if (newVal) { 
       $attr.ngIf = true; 
       unregisterWatcher(); 
      } 
     }); 

     ngIf.link.apply(ngIf, arguments); 
     ngShow.link.apply(ngShow, arguments); 
    } 
}; 
}]); 
+1

绝对有可能的,可以请你分享你尝试过什么时间执行ngIf只有一次,? ? – harishr 2014-11-03 08:51:30

回答

2

这可能是一个可能的解决方案:

myApp.directive("ngIfOnce", function() { 
return { 
    restrict: 'A', 
    transclude: true, 
    template: "<span ng-show='originalNgIf' ng-if='initialized' ng-transclude></span>", 
    scope:{ 
     ngIfOnce: '=' 
    }, 
    link: function (scope, attr) { 
     console.log(scope.ngIfOnce);    
     scope.$watch('ngIfOnce', function (newVal, oldVal) { 
      console.log("changed" + newVal); 
      scope.originalNgIf = newVal; 
      if (scope.initialized === undefined && scope.originalNgIf === true) scope.initialized = true; 

     }); 

    } 
    } 

} );

http://jsfiddle.net/wvg9g50b/

它transcludes的ngIfOnce内容和而ngShow,每次执行的变量传递作为一个属性改变

+0

它的工作原理!谢谢! – 2014-11-03 10:17:48