angularjsangularjs-directiveangular-templatecache

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?


Solution

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