Creating a custom repeater with ng-repeat

I want to create a custom repeater directive and pass the expression to ng-repeat inside the directive template.

The reason for this is to provide a cleaner interface in html, since I also include other under-the-hood directives.

http://jsfiddle.net/DeanIconWeb/Cg9RC/1/

Here is my html template:

<tr custom-repeater="person in people"> <td>{{person.name}}</td> <td>{{person.gender}}</td> <td>{{person.age}}</td> </tr> 

Here is my directive:

 app.directive("customRepeater", function(){ return { priority : 2000, restrict: 'A', replace : true, transclude : true, scope : { ngRepeatExp : "@customRepeater" }, template : "<tr ng-repeat='{{ngRepeatExp}}' ng-class-even=\"'even'\" ng-transclude></tr>" } }); 

While trying to do this work, I continued to get the error "The template must have one root element."

In the end, I did the following, but that is not what I really want.

 <tr ng-repeat="person in people" custom-repeater> <td>{{person.name}}</td> <td>{{person.gender}}</td> <td>{{person.age}}</td> </tr> 

Directive

 app.directive("customRepeater", function($compile){ return { priority : 2000, //must be compiled before the ng-repeat (priority 1000) restrict: 'A', compile : function(tElem, tAttrs){ tElem.attr("ng-class-even", "'even'" ); } } }); 
+4
source share
1 answer

You can use the $compile service to do something like this (add your other attributes / directives, as it seems to you, before you use the service):

http://jsfiddle.net/mQS4f/

 app.directive("customRepeater", function ($compile) { return { //priority: 2000, //restrict: 'A', // This is implicit //replace: true, //transclude: true, //template: "<tr ng-repeat='{{ngRepeatExp}}' ng-class-even=\"'even'\" ng-transclude></tr>" link: function (scope, element, attrs) { attrs.$set('ng-repeat', attrs.customRepeater); element.removeAttr('custom-repeater'); $compile(element)(scope); } } }); 
+3
source

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


All Articles