AngularJS - 传递对象到属性时,动态加载templateURL [英] AngularJS - dynamically load templateURL when passing object into attribute
问题描述
在我的控制器HTML我传递一个对象到一个指令这样:
In my controller HTML I am passing an object into a directive as such:
<div cr-count-summary countdata="vm.currentCountData"></div>
的 vm.currentCountData code>是从工厂返回的对象
我的指令,code是如下:
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';
}
}
}
}
我已经验证了 vm.currentCountData code>是上有一个
.TYPE
属性的有效对象。但是,它不承认它。我已经刚刚传入 countdata =存款
控制器中的HTML试图简化事情。我也改变了 attrs.countdata.type
只是 attrs.countdata code>,它并计算为字符串。
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.
当我把它设置为我已经指令如上图所示 templateUrl
功能似乎来评价控制器之前
When I have it set up as I have shown above the directive templateUrl
function seems to evaluate prior to the controller
我看了<一个href=\"http://stackoverflow.com/questions/21835471/angular-js-directive-dynamic-templateurl\">this,但它似乎只计算字符串
I've looked at this, but it seems to only be evaluating strings
我需要什么,才能做到让ATTRS识别对象?
What do I need to do in order to allow attrs recognize the object?
推荐答案
这是不可能以这种方式,因为在评估 templateUrl
函数角度的时间不有任何作用域变量,指令的编译功能产生 $ p $砰砰
&放后范围被创建; postLink
。
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
.
我倒是preFER您使用的指令模板中 NG-包括
指令,然后在条件的基础在里面做负载所需的模板。
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.
标记
<div cr-count-summary count-data="vm.currentCountData"></div>
指令
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>"
}
}
这篇关于AngularJS - 传递对象到属性时,动态加载templateURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!