我在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);
}
};
}]);
絕對有可能的,可以請你分享你嘗試過什麼時間執行ngIf只有一次,? ? – harishr 2014-11-03 08:51:30