Dynamic template in attribute-based directive?

I saw a bunch of questions very similar to this, but I'm new to Angular, so they are not entirely clear. Here is my attitude:

I have a directive defined:

robus.directive("titlebar", function() { return { restrict: "E", scope: { title: '@title' }, template: "<header class='bar-title'><h1 class='title'>{{title}}</h1></header>", replace: true } }); 

I use this directive as follows:

 <titlebar title="{{workout.name}}"></titlebar> 

Ideally, I want to add additional attributes to it, for example:

 <titlebar title="{{workout.name}}" editButton="true" closeButton="true"></titlebar> 

How to handle them in a template definition? I read about the $compile() function that I need to override, but I don't know how to do it. Templates are just strings, so I feel like I can just make them inline and refer to them as separate files.

Thanks!

+3
source share
1 answer

Make them available in the directive by adding them to the scope statement, just like you have a header. Then add the buttons to the template and conditionally define them like this:

 robus.directive("titlebar", function() { return { restrict: "E", scope: { title: '@title', edit: '@editButton', cancel: '@cancelButton' }, template: "<header class='bar-title'><h1 class='title'>{{title}}</h1><span ng-show='edit'>Edit</span><span ng-show='cancel'>Cancel</span></header>", replace: true } }); <titlebar title="{{workout.name}}" edit-button="true" cancel-button="false"></titlebar> 

Note that this is editButton in the directive and edit button in HTML; There is a built-in conversion from hyphen to camel case, which will bite you if you do not know about it.

In addition, I recommend using transclude here, since I think it will read more cleanly:

 robus.directive("titlebar", function() { return { restrict: "E", scope: { edit: '@editButton', cancel: '@cancelButton' }, template: "<header class='bar-title'><h1 class='title' ng-transclude></h1><span ng-show='edit'>Edit</span><span ng-show='cancel'>Cancel</span></header>", transclude: true, replace: true } }); <titlebar edit-button="true" cancel-button="false">{{workout.name}}</titlebar> 
+3
source

Source: https://habr.com/ru/post/1488779/


All Articles