RoyalKnight
RoyalKnight

Reputation: 139

Init angular app in jQuery's ajax success callback

A jQuery ajax request loads the HTML of an angular app (out of multiple independent angular apps) and injects it in the DOM (simplified code):

$.ajax({
  'url': 'url-to-random-angular-app.html',
  'success': function(data) {
    var content = $(data).find('[data-id]');
    //var content = '<div data-id="5"><div ng-app="MyRandomApp" ng-controller="MyRandomAppController">[...]</div></div>';
    //angular.???.$compile(content);
    $('#container').html(content);
  }
});

My problem is, that the angular app is not working, because it's not initialized somewhere. How can I init the angular app in the jQuery success callback?

Upvotes: 1

Views: 833

Answers (2)

narrowtux
narrowtux

Reputation: 703

Angular.js automatically bootstraps on the DOMContentLoaded event. This event will only be called once, so Angular won't automatically initialise after you put the ajax-loaded html into your DOM.

The official Angular documentation shows this way of manually invoking the bootstrap of your Angular app:

angular.bootstrap(document, ['myApp']);

Please note that the myApp value is of importance here.

Sidenote

I don't know how complex your project is, but you could probably replace your Uber-jQuery site by combining all your Angular-apps into one. Use ngRoute or ui-router to load different pages.

Upvotes: 1

schellmax
schellmax

Reputation: 6094

you can initialize your angular app at any given time using:

angular.bootstrap(document, ['MyRandomApp']);

also see https://docs.angularjs.org/guide/bootstrap#manual-initialization

Upvotes: 3

Related Questions