我在理解指令属性 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