我在理解指令屬性 vs 範圍變量傳遞給指令時遇到一些困難。
我正在制定一個動態加載正確模板的指令,具體取決於內容類型。 當我使用linker
功能,使用範圍變量做切換的事情工作良好。動態模板和範圍變量
如果我使用:
<mydirective ng-repeat="item in items" content="item" type="item.type"></mydirective>
我通過包含數據的對象content
用於填充模板和該對象內我有一個type
屬性我使用用於選擇的模板。
這是我的指令定義(一些代碼省略):
//[...]
linker = function(scope, element, attrs){
//templates is a service I use to retrieve the templates
loaderPromise = templates.getTemplate(scope.content.type)
promise = loaderPromise.success(function(html){
element.html(html)
}).then(function(response){
element.replaceWith($compile(element.html())(scope))
})
}
return {
restrict : "E",
replace: true,
scope: {
'content': "="
},
link : function(scope, element, attributes){
linker(scope, element, attributes)
}
//[...]
}
現在,而不是這個,我想一個函數傳遞給「templateUrl」,像這樣:
return {
restrict : "E",
replace: true,
scope: {
'content': "="
},
templateUrl : function(element, attributes) {
// I don't access to the scope but only to the attributes
attributes.$observe(attributes.content.type, function(value){
if(value) {
// templates is a service
return templates.getTemplateUrl(value.type)
}
})
}
//[...]
}
現在,這將不起作用要麼我觀察attributes.content.type
或attributes.type
。這些屬性將始終爲undefined
。
我也嘗試添加傳遞給該指令type
爲範圍變量:
scope: {
'content': "="
'type': '='
}
但被繼續undefined
。
所以基本上我真的很困惑的使用attributes
VS使用variable scopes
編輯:
我猜它是與NG-重複。如果我把一個斷點上線
attributes.$observe(attributes.content.type, function(value){
,我檢查attributes
值我得到
$$element: jQuery.fn.init[1]
$attr: Object
content: "item"
ngRepeat: ""item in items"
,所以我想content
尚未進行評估,這就是爲什麼attributes.content.type
是undefined
。想知道爲什麼..
我的'模板'服務是同步的。我已經更新了這個問題,我想這與ng-repeat更相關,但並非100%肯定。 – Leonardo 2014-10-05 14:55:58
@Leonardo,我編輯了答案 – 2014-10-06 15:38:20
所以基本上你的最後一個解決方案看起來與我的第一個解決方案非常相似一個工作),不是嗎? – Leonardo 2014-10-22 13:34:14