0

Suppose I have a table such that it adds rows when user click a button. The row adding code looks like this:

  success: function (data, textStatus, jqXHR) {
      $row = $('a#temp').parents('table').find('tr[id$=' + m + ']');
      var $new_rows = $(data['payload'].join("\n"));
      $row.after($new_rows);
  }

Whereas the success is a non-angular callback function such that the ajax response has came back.

The payload will contain the HTML code along with the controller and directive inside the HTML.

I saw that the row is added correctly but I don't see the newly added row controller and directive get initialize.

Any suggestion is welcome.

Thanks

Kintarō
  • 2,947
  • 10
  • 48
  • 75
  • 1
    You should be doing the data call in Angular via `$http` or `$resource` - then you build your data model, and your view is constructed off that via directives (`ngRepeat`, `ngShow`, `ngHide`, etc) - don't blend jQuery with Angular and then try to solve the complex problem that it creates. – tymeJV Mar 26 '15 at 23:03

1 Answers1

0

Even though this is a very bad idea, as @tymeV mentioned in their comment, you should be able to do what you want using the $compile service.

Just inject $compile into whatever function contains the AJAX call and (so long as you also have the $scope available), you can change your success handler to:

success: function (data, textStatus, jqXHR) {
    $row = $('a#temp').parents('table').find('tr[id$=' + m + ']');
    var $new_rows = $(data['payload'].join("\n"));
    $row.after($new_rows);
    $compile($new_rows)($scope);
    // if this is definitely the success handler for a jQuery.ajax() request or similar
    // then do the following. Otherwise, remove it.
    $scope.$digest();
}

This should be a last resort though. You really need to try and abandon relying on jQuery, especially to do DOM manipulation, and use the Angular directives instead. It will be much easier for you and anyone else who has to look at and maintain your code to understand.

Remember the old adage, "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability." (see this question for who said this). The violent psychopath who knows Angular will not think fondly of you for committing this cardinal sin in terms of AngularJS development.

Community
  • 1
  • 1
GregL
  • 37,147
  • 8
  • 62
  • 67