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?

1
  • 1
    use count-data="..." to refer on scope as countData:"="... on scope, camel case will find by hyphen separated attribute of html tag Commented Aug 13, 2015 at 18:48

1 Answer 1

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>"
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, I was having a hard time figuring out why templateURL was being evaluated prior to the controller
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.