ngIf一次有角度

时间:2014-11-03 08:39:02

标签: angularjs angularjs-directive

我正在使用Angular应用程序上的标签,使用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在设置了真值后继续工作:

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 个答案:

答案 0 :(得分: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/

它转换ngIfOnce内容并仅执行一次ngIf,而每次作为属性传递的变量更改时都会执行ngShow