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.


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


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.remove = function(index) {
$scope.array.splice(index, 1)}

Here is an example

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:


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

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