Cheng Locke Cheng Locke - 5 months ago 20
AngularJS Question

Using ng-repeat to repeat different directives?

I define different directives like this:

var app = angular.module('myApp',["ngTouch"]);

app.directive('controlLed',function() {
return {
restrict: 'E',
replace: true,
scope: true,
templateUrl: 'controlLed.html'
}
});

app.directive('controlPlug',function() {
return {
restrict: 'E',
replace: true,
scope: true,
templateUrl: 'controlPlug.html'
}
});

app.directive('controlTemp',function() {
return {
restrict: 'E',
replace: true,
scope: true,
templateUrl: 'controlTemp.html'
}
});

app.directive('controlDoor',function() {
return {
restrict: 'E',
replace: true,
scope: true,
templateUrl: 'controlDoor.html'
}
});


each directive has a different view model. Now I use ajax to return a json structure like this:

"device_list":{
"d0": {
name:led1,
model:controlLed
},
"d1": {
name:led2,
model:controlLed
},
"d2": {
name:plug1,
model:controlPlug
},
"d3": {
name:Temp1,
model:controlTemp
},
"d4": {
name:Door,
model:controlDoor
}
}


I want to use the ng-repeat to generate the following view of the results:

<div class="content">
<control-led></control-led>
<control-led></control-led>
<control-plug></control-plug>
<control-temp></control-temp>
<control-door></control-door>
</div>


What should I do?

Answer

Loop over you JSON data to create the HTML you require and utilize the $compile service to compile the generated HTML like below

var app = angular.module('myApp',[]);

app.controller('mCTRL',function($scope){
  $scope.myJSONData=[{
       name:'led2',
       model:'controlplug'
    },{
       name:'led1',
       model:'controlled'
    }]

})

Your directives

app.directive('controlled',function() {
   return {
       restrict: 'E',
       scope: true,
        replace:true,
       template: '<div>controlLed.html</div>'
   }
});

app.directive('controlplug',function() {
    return {
        restrict: 'E',
        scope: true,
        replace:true,
        template: '<div>controlPlug.html</div>'
    }
});

Create a new directive which will create dynamic template based upon your JSON data

app.directive('main',function($compile){
  return{
    restrict: 'E',
       replace: true,
       link(scope,elem,attrs)
       {
         debugger;
         var html='';

         for(var i=0;i<scope.myJSONData.length;i++)
         {
           debugger;
           var model=scope.myJSONData[i].model;
           html+=$compile("<div><"+model+"><"+model+"/><div/>")(scope).html()
         }
         elem.replaceWith(html);

       }

  }

})

Note: This way you can make your code generic and in future if you have to add some more directives you only have to add it in your JSON and it will pick the correct directive and render it, you don't have to change your view every time for it.