Angular directives. How to choose a template based on attribute values?

I am developing a widget where I want to display some messages / text one by one. I want to change the message template based on the type of message.

my current directive setting is as follows

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 } }; }); 

The directive is used as follows

 <div ng-repeat="(key, value) in chatUser.msg"> <data-cus-msg-text msg="value.type"></data-cus-msg-text> </div> 

Now my question is: -

  • Is it possible to return one of several lines (templates) from the template function itself based on the actual value of the msg attribute. I tried to access attrs.msg in the template function, and it return value.type .

  • If this is not the case, is it good to manipulate the template in linker or do I need to move it to the compile function?

+6
source share
2 answers

To display another template based on value.type , you can use the 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> 

In addition, if I understood your second question: the manipulation of an uncompiled directive should be performed in the compile function, all manipulations that occur after compilation should go in the link function.

Documents for ngSwitch

EDIT : +1 for Sebastian to understand what you wanted. However, what it offers is basically reinventing the wheel, as it essentially compiles and inserts the template manually (which ngSwitch means to you). In addition, you can access the attributes that you put in your directive through the attrs argument of the link function.

+7
source

In the template function, you do not have access to the scope your directive. If you want to control what the rendering gets, you can do it using conditional logic (e.g. ng-switch ) in the global template, as suggested by the simulated one, or use the link function:

 .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)); } }; }); 
+4
source

All Articles