rocco rocco -4 years ago 183
AngularJS Question

Push trustAsHtml with directive to ng-repeat

For example I have some ng-repeat with default rows without remove button and i want to add new rows that can be removed. Remove function does't work in added row. I know that i can solve this problem by using directive and $compile but i dont understand how to use it with ng-repeat.

HTML



<body ng-app="TestApp" ng-controller="Test">
<ul>
<li ng-repeat="o in array">
<div id="name">{{ o.name }}</div>
<div id="remove" ng-bind-html="o.remove"></div>
</li>
</ul>
<fieldset>
<input ng-model="inputname">
<button ng-click="addRow(inputname)">Add row</button>
</fieldset>
</body>


JS



angular.module('TestApp', []).controller("Test", function($scope, $sce) {
$scope.array = [{name: "Test1"},{name: "Test2"},{name: "Test3"},{name: "Test4"}]

$scope.addRow = function(name){
var a = { name: name,
remove: $sce.trustAsHtml("<button ng-click='removeRow($index)' </button>")
}
$scope.array.push(a)}
$scope.remove = function(index) {
$scope.array.splice(index, 1)}
})


Here is an example http://plnkr.co/edit/0WFmvT?p=preview

Answer Source

Checkout this link, Using ng-bind-html and $sce.trustAsHtml create a string with ng-model binding have added a compile-template directive, updated plnkr: http://plnkr.co/edit/veKAGjXoJ7DKeC233wbj?p=preview

In HTML :

<ul>
    <li ng-repeat="o in array"><div id="name">{{ o.name }}</div>
        <!-- added compile-template -->
        <div id="remove" ng-bind-html="o.remove" compile-template></div>
    </li>
</ul>

In JS :

.directive('compileTemplate', function($compile, $parse){
    return {
        link: function(scope, element, attr){
            var parsed = $parse(attr.ngBindHtml);
            function getStringValue() {
                return (parsed(scope) || '').toString();
            }

            // Recompile if the template changes
            scope.$watch(getStringValue, function() {
                $compile(element, null, -9999)(scope);  // The -9999 makes it skip directives so that we do not recompile ourselves
            });
        }
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download