我在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