For the following angularjs directives:
app = angular.module('ngApp');
app.value('objects', [
{id: 1, name: 'Jane Doe', active: true},
{id: 2, name: 'Test Biz', active: false},
{id: 3, name: 'Another Business', active: false}
]);
app.directive('myDirective', function (objects) {
return {
template: '<ul></ul>',
replace: true,
compile: function(element, attrs) {
for(var i=0;i<objects.length;i++) {
element.append('<div other-directive object={{object}}></div>');
}
}
};
})
.directive('otherDirecctive', function() {
return {
template: '<li>{{object.name}}',
replace: true,
scope: { object: '=' }
});
And this bit of html:
<div my-directive></div>
How do I pass each object into the sub-directive? Is there a better overall way to structure this code?
I would suggest using just one directive and harness ng-repeat
in the template:
app.directive('myDirective', function (objects) {
return {
link: function(scope,element,attrs){
scope.objects = objects;
},
template: '<ul><li ng-repeat="o in objects">{{o.name}}</li></ul>'
};
});
But if you still want to use the second directive, you can use as is, just change the template of the first to:
'<ul><li ng-repeat="o in objects" other-directive object="o"></li></ul>'
Demo: Here is a fiddle