我正在开发一个小部件,我想一个接一个地呈现一些消息/文本.我想根据消息类型更改消息的模板.
我当前的指令设置如下
directive('cusMsgText',function(){
return {
restrict: 'E',template:function(elements,attrs){
return '<div></div>';
},link: function($scope,iElm,iAttrs,controller) {
//add children to iElm based on msg values in $scope
}
};
});
该指令使用如下
<div ng-repeat="(key,value) in chatUser.msg">
<data-cus-msg-text msg="value.type"></data-cus-msg-text>
</div>
现在我的问题是 – :
>是否可以从中返回多个字符串(模板)中的一个
模板函数本身基于属性的实际值
味精.我尝试在模板函数中访问attrs.msg
return value.type.
>如果没有,那么在链接器或I下操作模板是否合适
需要将其移动到编译功能?
解决方法
要基于value.type呈现不同的模板,您可以使用ng-switch语句:
<div ng-switch="value.type">
<div ng-switch-when="type1">
//...template for type 1 here...
</div>
<div ng-switch-when="type2">
//...template for type 2 here...
</div>
</div>
另外,如果我理解你的第二个问题:应该在编译函数中完成对未编译指令的操作,编译后发生的所有操作都应该在链接函数中进行.
Docs for ngSwitch
编辑:1塞巴斯蒂安了解你想要的.然而,他提议的基本上是重新发明轮子,因为它实际上是手动编译和插入模板(这是ngSwitch为你做的).此外,您可以通过链接函数的attrs参数访问您在指令中放置的属性.