2014-05-02 47 views
6

我正在开发一个小部件,我想呈现一些消息/文本此起彼伏。我想根据消息的类型更改消息的模板。Angular指令 - 如何根据属性值选择模板?

我目前的指令设置如下

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> 

现在我的问题是 - :

  1. 是否有可能返回一个多个字符串(模板)从 模板函数本身基于实现属性 msg的AL值。我试着在模板函数访问attrs.msg它 返回value.type

  2. 如果不是那么操纵linker或我 需要把它移动到compile函数是好的吗?

回答

7

为了使基于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> 

另外,如果我理解你的第二个问题:未编译指令的操作应在compile函数来完成,编译后发生的所有操作应该在link函数中进行。

Docs for ngSwitch

编辑:+1塞巴斯蒂安理解你想要的东西。然而,他所提出的基本上是重新发明了轮子,因为它本质上是编译和手动插入模板(这就是ngSwitch为你所做的)。此外,您还可以通过link功能的attrs参数访问您的指令,你把属性。

+0

我无法访问实际值提供属性的指令。在模板函数下,value.type是一个字符串。 –

+0

在你提供的例子,你的指令有一个'msg'属性。如果我明白了,可以通过该属性将该类型传递给指令。您可以在该值上进行切换,但我没有看到问题所在。另外,“模板函数”是什么意思? '链接'功能? – link

4

template功能,你不必访问您的指令的scope。如果你想控制由simoned什么得到渲染,你可以做到这一点使用条件逻辑(如ng-switch)在全球模板的建议或使用link功能:

.directive('cusMsgText', function($compile) { 
    return { 
    restrict: 'E', 
    scope: { 
     msg: '=', 
     item: '=' 
    }, 
    link: function(scope, element, attrs) { 
     templates = { 
     x: '<div>template x {{item.name}}</div>', 
     y: '<div>template y {{item.name}}</div>' 
     }; 

     var html = templates[scope.msg]; 
     element.replaceWith($compile(html)(scope)); 
    } 
    }; 
}); 
+0

是不是可以解析模板函数中的属性值? +1。 –