I want this
$scope.name = 'Angular';
$scope.list = ['foo: {{name}}', 'bar: {{name}}'];
<div ng-repeat="template in list" compile="template"></div>
to be
<div real="foo: Angular"></div>
<div real="bar: Angular"></div>
So i use $compile:
$compileProvider.directive('compile', function ($compile) {
return function (scope, element, attrs) {
scope.$watch(
function (scope) {
return scope.$eval(attrs.compile);
},
function (value) {
//element.html(value);
//$compile(element.contents())(scope);
element.attr("real", value);
element.removeAttr("compile");
$compile(element)(scope);
}
);
};
})
but, it output:
<div real="foo: Angular"></div>
<div real="foo: Angular"></div>
<div real="bar: Angular"></div>
<div real="bar: Angular"></div>
so what's the problem ?
Alternatively, you can use the pre link function : http://plnkr.co/edit/VIOAX1akTPF68DYxZQcQ
Try this instead:
DEMO
Explanation:
When you put your directive on the same element with
ng-repeat
and call$compile(element)(scope);
, your element is recompiled including the ng-repeat, causing theng-repeat
to run one more time. When I also remove the ng-repeat in the directive, it works:DEMO
This solution is not recommended because we hard-code the
element.removeAttr("ng-repeat");
Remember to also apply
priority:1500
andterminal:true
to the directive to avoid compiling again after angular has compiled the element:For more information about these 2 settings. Check out Add directives from directive in AngularJS