Jon Harding
Jon Harding

Reputation: 4946

Change templateURL of directive dynamically after $http.get()

I'm working on 'skeleton' loading the UI in different components. I have a directive that I'm loading a template initially (this template has low opacity and looks like a mock table). Once I get the data I need in an http.get() then I want to change the templateUrl of the directive. Below is what I've tried so far.

function registers($log, $state, $templateCache, currentCountData, storeFactory) {
    var directive = {
        restrict: 'A',
        scope: true,
        templateUrl: '/app/shared/tableMock/tableMock.html',
        link: link
    };

    return directive;

    function link(scope, element, attrs) {
        storeFactory.getRegisters().then(function (data) {
            scope.registers = data.registers;
            $templateCache.put('/app/dashboard/registers/registers.html');
        });
    }
}

I'm not sure I'm on the right track. I can step through and see the storeFactory return the correct data from my factory. How can I then change the templateUrl of the directive?

Upvotes: 0

Views: 528

Answers (2)

edrpls
edrpls

Reputation: 317

For cases like this I usually do something like this in my directive template:

<div ng-switch="viewState">
  <div ng-switch-when="gotRegisters">
   Content for when you get the registers
  </div>
  <div ng-switch-default>
   For when you don't have the registers
  </div>
</div>

This way you could just change a variable to show your content ie scope.viewState = 'gotRegisters'; instead of waiting for it to download after you already downloaded your registers.

Upvotes: 1

Jon Harding
Jon Harding

Reputation: 4946

With a help from this question I was able to come up with this

function link(scope, element, attrs) {                        
    storeFactory.getRegisters().then(function (data) {
        scope.registers = data.registers;
        $http.get('/app/dashboard/registers/registers.html', { cache: $templateCache }).success(function (tplContent) {
            element.replaceWith($compile(tplContent)(scope));
        });
    });
}

tplContent correlates to the response of the $http.get(). It's the html in the registers.html file. element represents the directive itself.

Upvotes: 0

Related Questions