简体   繁体   中英

$compile dynamically added row to use ngClick - AngularJS

I'm trying to dynamically add some rows to a table by clicking on a "plus" icon. It works but, in these rows I have a "trash" icon that allows me to delete that row.

The delete function works well with the static rows but it's not called by the dynamically added rows. I think I need to $compile the rows but can't find how to use it well.

Here are the static rows

<tbody class="fields-to-edit">
<tr style="display: none">
    <td>trash</td>
    <td>field_name</td>
    <td>data</td>
</tr>
<tr ng-repeat="field in fields">
    <td class="doc-viewer-buttons">
        <a ng-click="deleteRow($event)"><i tooltip="Delete the row" tooltip-placement="right" class="fa fa-trash"></i></a>
    </td>
    <td contenteditableclass="doc-viewer-field">
        {{field}}
    </td>
    <td>
        <div class="doc-viewer-value" contenteditable ng-bind-html="typeof(formatted[field]) === 'undefined' ? hit[field] : formatted[field] | trustAsHtml"></div>
    </td>
</tr>

This is how I add a new row in my main directive :

$scope.addRow = function () {
  $('.fields-to-edit').append($('<tr><td class="doc-viewer-buttons"><a ng-click="deleteRow($event)"><i tooltip="Delete the row" tooltip-placement="right" class="fa fa-trash"></i></a></td><td contenteditable class="doc-viewer-field">FIELDNAME</td><td><div class="doc-viewer-value" contenteditable>CONTENT</div></td></tr>'));
};

$scope.deleteRow = function ($event) {
  angular.element(angular.element($event.currentTarget).parent()).parent().remove();
};

The ng-click contained in the new row has no effect, that's why I think I should use $compile, but how and where?

Don't manipulate the DOM - change the data to add to the DOM. In your case - simply append to the fields array

$scope.addRow = function () {
    $scope.fields.push("Some new field");
}

Then deleteRow should take the row index, splice it from the data array:

$scope.deleteRow = function(index) {
    $scope.fields.splice(index, 1);
}

<a ng-click="deleteRow($index)"><i tooltip="Delete the row" tooltip-placement="right" class="fa fa-trash"></i></a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM