I have a custom directive myItems
that is rendering a list of items using another directive myItem
via ng-repeat
:
app.directive('myItems', function() {
return {
scope:{items:"="},
restrict:"E",
template:"<div my-item ng-repeat='item in items'></div>"
};
});
Each item contains information (such as a color) that has be used for styling the elements. This works fine so far if I use the templating approach:
app.directive('myItem', function() {
return {
restrict:"A",
template:"<div ng-style='{color:item.color}'>myItem: {{item.name}}</div>",
replace:true
};
});
To support more involved features, I now want to rebuild the same functionality if my-item
by manually creating all the needed stuff including the ng-style:
app.directive('myItem', function($compile) {
return {
restrict:"A",
compile: function(element) {
element.removeAttr('my-item');
element.text('myItem: {{item.name}}');
element.attr('ng-style', '{color:item.color}'); // Why does it have no effect?
var compileElement = $compile(element);
return function link(scope, elem, attr) {
compileElement(scope); // Why does binding with {{item.name}} even work without this statement?
};
}
};
});
Interestingly enough databinding using {{item.name}}
works while ng-style
does not.
Here is a fiddle showing both approaches described above.
I am aware of the similar question. But I think it does not apply here since I have no explicit statements about the scope of the my-item
directive.