Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngIf once with angular [closed]

I'm using tabs on a Angular app, using ngIf to lazy load the directives and controls inside them when the users needs to. The problem is that I don't want to recreate the tab if the users navigate through them, and with that in mind I'm using this trick to initialize the tab just once and show it when then users needed:

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

What I want to achieve is implement this behaviour with a custom directive, something like ng-if-once="tab.show", reusing the core ngIf and ngShow directives if possible. Any ideas?

EDIT

This is my temporal solution, but ngIf keeps working after a truthy value is set:

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);
    }
};
}]);
like image 700
Javier Marín Avatar asked Dec 08 '25 21:12

Javier Marín


1 Answers

This could be a possible solution:

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/

It transcludes the ngIfOnce content and executes the ngIf only once, while the ngShow is executed every time the variable passed as an attribute changes

like image 181
Michael Avatar answered Dec 11 '25 11:12

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!