-1

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

rocco
  • 37
  • 7
  • 1
    Will there be different HTML in `remove` or why are you adding it as a `string` and not to your template? – Arg0n Mar 23 '17 at 14:15
  • Yeah, as @Arg0n says, the easier solution would seem to be to include the ` – Daniel Beck Mar 23 '17 at 14:19

1 Answers1

0

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
            });
        }
    }
});
Community
  • 1
  • 1
Aks1357
  • 1,062
  • 1
  • 9
  • 19