2014-11-03 133 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