Directive code:
.directive('replace', function($compile) {
return function (scope, element) {
element.html(element.html().replace("Hej", "Hey!"));
$compile(element.contents())(scope);
}
});
})
HTML
<div ng-controller="GreeterController">
<div replace>Hej <div ng-repeat="e in arr">{{ e }}</div>
</div>
</div>
Controller
app.controller('GreeterController', ['$scope', function($scope) {
$scope.arr = [1, 2, 3, 4];
}]);
As the title says, ng-repeat
doesn't work when I'm using the directive from above on HTML which contains it.
But once I remove that line which uses .replace()
command to replace part of HTML then ng-repeat
starts working for some reason.
Does anyone know where's the actual problem?
I have tried everything and I still seem to not get it why it doesn't work as it should.
Solved it like this:
Live example
You should let Angular and its change detection cycle do the HTML manipulation for you, instead of directly changing it yourself.
I've edited your example to use scope bindings to achieve what you wanted:
Note: I removed "scope: false" as that is the default behaviour.
EDIT: Since you must replace HTML in place here's a solution with jQuery:
The manipulation can also be done in the compile phase:
The original problem was caused because the linking of the
ng-repeat
directive was done before the element with that directive is replaced with the replace operation. The watchers associated with theng-repeat
directive then operate on elements that are no longer attached to the visible DOM.By moving the replace operation to either the compile phase or the preLink phase, the replacing of the element that has the
ng-repeat
directive is done before theng-repeat
directive is linked. The watchers associated withng-repeat
directive then work with the replaced DOM.