Dynamically select a directive based on data

I am trying to populate a table based on an array of objects. This array does not contain objects of the same type, and for each row I need a completely different style and the onclick function, basically, a completely different behavior. For instance,

var data=[
  {
    type:'dir-b',
    data: { ... }
  },
  {
    type:'dir-b',
    data: { ... }
  },
  {
    type:'dir-c',
    data: { ... }
  }
]

For the dirB object type, I need a template and controller, and for dirC, a completely different function and template.

I found a solution to create 3 directives. One of them will work to define one of the other two directives to add based on the data.

.directive("dirA", function($compile){
  return{
    restrict:'A',
    priority:1000,
    terminal:true,
    link: function(scope, element, attribute){
      element.removeAttr("dir-a");//prevent endless loop
      element.attr(attribute.type,"");
      $compile(element)(scope);
    }
  }
})
.directive("dirB", function($compile){
  return{
    restrict:'A',
    replace:true,
    link: function(scope, element, attribute){
        console.log("dirA");
    }
  }
})
.directive("dirC", function($compile){
  return{
    restrict:'A',
    replace:true,
    link: function(scope, element, attribute){
        console.log("dirC");
    }
  }
});

<tr dir-a type='{{d.type}}' ng-repeat='d in data'/> . dirA 0, , , , 1000, b.type . - ?

+4
2

, , , .

<table>
  <tbody ng-repeat='d in data'>
    <tr ng-if='d.type=="dir-b"' dir-b></tr>
    <tr ng-if='d.type=="dir-c"' dir-c></tr>
  </tbody>
</table>

- ng- , , tbody , . , , .

0

ngSwitch .

Plnkr

HTML

<div ng-repeat="(key, d) in data track by $index">
  <div class="tbody" ng-switch on="d.type">
    <div class="row" ng-switch-when="dir-b" dir-b>{{d}}</div>
    <div class="row" ng-switch-when="dir-c" dir-c>{{d}}</div>
  </div>
</div> 

dirB dirC.

html-, , ?

0

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


All Articles