Say I have three (element) directives: <x/> <y/> and <z/>
.
module.directive('x', function() {
return {
restrict: 'E',
template: '<div class="x">{{identifier}}</div>'
}
});
the directives for <y/> and </z>
are similar.
I also have an array of page configuration objects. Each object has a type and an identifier. The type denotes a directive, and the identifier is some data to be shown inside the template of the directive, in the directive fragment above shown as {{identifier}}.
var pageElements = [
{type: 'x',identifier:'123'},
{type: 'z',identifier:'adf'},
{type: 'x',identifier:'qwe'},
{type: 'y',identifier:'4ed'},
{type: 'y',identifier:'576'}
]
In my page I want something like this:
<div id="containingDiv" ng-repeat="elem in pageElements"></div>
How to set up my directives etc so that the following output will be generated, and be updated when the pageElements array changes?
<div id="containingDiv">
<div class="x">123</div>
<div class="z">adf</div>
<div class="x">qwe</div>
<div class="y">4ed</div>
<div class="y">576</div>
</div>
In your controller you would do something like this:
function myController($scope){
$scope.pageElements = [
{type: 'x',identifier:'123'},
{type: 'z',identifier:'adf'},
{type: 'x',identifier:'qwe'},
{type: 'y',identifier:'4ed'},
{type: 'y',identifier:'576'}
];
}
Then in your html, as bmleite suggested you would have:
<div id="containgDiv">
<div class="{{elem.type}}" ng-repeat="elem in pageElements">{{elem.identifier}}</div>
</div>
This would generate
<div id="containingDiv">
<div class="x">123</div>
<div class="z">adf</div>
<div class="x">qwe</div>
<div class="y">4ed</div>
<div class="y">576</div>
</div>
In your angular.module(.... you could then wire up the directives to the class. Every time the pageElements array gets updated, the list will either be changed by adding the new, editing the current ones or removing the ones that are no longer there. Angular takes care of that grunt work for you.