0

I have a directive that is shown under some condition using ng-if.

Once the condition is met, the link function triggers and I use $compile to replace the directive content with some HTML blocks.

Then at some point the directive is hidden and when it is shown again, the same code is called to recreate the HTML blocks. I have tried setting a flag on the scope, but once ng-if is set to false, the scope values are lost.

What would be the correct approach to avoid recreating the HTML blocks each time ng-if set back to true ? In other words, how can I make sure the HTML blocks are only generated the first time ng-if is set to true ?

  link: function (scope, element, attrs) {
            if (!scope.initialized) {

                $http.get('some url to method on server' } }).then(function (response) {
                    var list = '';
                    response.data.forEach(function (link) {
                        list += '<a href=' + link + '>' + link + '</a>';
                    });
                    element.html('<div>' + list + '</div>');
                    $compile(element.contents())(scope);
                    scope.initialized = true;
                }, function (response) {

                });
            }
Sam
  • 13,934
  • 26
  • 108
  • 194
  • I think the directive you're looking for is **[`ngHide`](https://docs.angularjs.org/api/ng/directive/ngHide)**. – ryeballar Aug 04 '15 at 15:01
  • If I use this directive, the HTML blocks are generated regardless the value of ngHide. They are not shown, but they are generated, which is not efficient since the directive appears multiple times in my page. – Sam Aug 04 '15 at 15:02
  • 1
    What is the higher level problem of having html generated each time? – charlietfl Aug 04 '15 at 15:06
  • Check out this post: http://stackoverflow.com/questions/19177732/what-is-the-difference-between-ng-if-and-ng-show-ng-hide – lintmouse Aug 04 '15 at 15:06
  • the link function is generated for each directive, so if you add the directive to the DOM it will execute it again. – gr3g Aug 04 '15 at 15:07
  • ok, I've edited my post with the code. Basically this directive is repeated multiple times on the screen. So I don't want to make unnecessary calls to the server. Only once, when ng-if is set to true. The next time it is set to true, the same HTML blocks should be re-used (I understand it is the case with ng-if, however the call to the server is still executed :( ) – Sam Aug 04 '15 at 15:14
  • How about something like this? **[`plnkr`](http://plnkr.co/edit/L0EKraZi3b1CH27mMwCZ?p=preview)** – ryeballar Aug 04 '15 at 15:54

0 Answers0