问题
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:
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>"
}
}
来源:https://stackoverflow.com/questions/31995874/angularjs-dynamically-load-templateurl-when-passing-object-into-attribute