1

In my controller HTML I am passing an object into a directive as such:

<div cr-count-summary countdata="vm.currentCountData"></div>

The vm.currentCountData is an object that is returned from a factory

My directive code is below:

function countSummary() {
    var directive = {
        scope: {        
            countData: '='
        },
        link: link,
        templateUrl: function(element, attrs) {
            if (attrs.countdata.type === 'Deposit') {
                return 'app/count/countsummary/countDeposit.html';
            } else {
                return 'app/count/countsummary/countRegisterSafe.html';
            }
        }
    }
}

I have verified that vm.currentCountData is a valid object with a .type property on it. However, it doesn't recognize it. I have tried simplifying things by just passing in countdata="Deposit" in the controller HTML. I've also changed attrs.countdata.type to just attrs.countdata and it does evaluate as the string.

When I have it set up as I have shown above the directive templateUrl function seems to evaluate prior to the controller

I've looked at this, but it seems to only be evaluating strings

What do I need to do in order to allow attrs recognize the object?

Community
  • 1
  • 1
Jon Harding
  • 4,928
  • 13
  • 51
  • 96
  • 1
    use count-data="..." to refer on scope as countData:"="... on scope, camel case will find by hyphen separated attribute of html tag – Joao Polo Aug 13 '15 at 18:48

1 Answers1

2

This is not possible in this way, because at the time of evaluating templateUrl function angular doesn't have any scope variable, scope gets created after the compile function of directive generates preLink & postLink.

I'd prefer you to use ng-include directive inside the directive template, and then on basis of condition do load the desired template in it.

Markup

<div cr-count-summary count-data="vm.currentCountData"></div>

Directive

function countSummary() {
    var directive = {
        scope: {        
            countData: '='
        },
        link: link,
        template: "<div ng-include=\"countdata.type === 'Deposit' ? "+
                     "'app/count/countsummary/countDeposit.html' :" + 
                    "'app/count/countsummary/countRegisterSafe.html'\">"+
                  "</div>"
    }
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • thanks, I was having a hard time figuring out why templateURL was being evaluated prior to the controller – Jon Harding Aug 13 '15 at 19:25
  • With not having access to scope, is there anyway to make this into a function? It's possible that there might be different templates to load – Jon Harding Aug 13 '15 at 19:31