RonLugge RonLugge - 3 months ago 18x
jQuery Question

How do I tell angular to scan the DOM after using AJAX to insert new content?

I've working on a project that uses AJAX to load content, and would like to load a bit of content that will be developed using AngularJS. After I load the content in via AJAX, it just sits there -- Angular doesn't recognize the angular directives I've added. How do I get AngularJS to scan the new code and process it?

var ajaxLoad = function(obj){
$('.target').load('dynamiclyDeterminedHTMLTarget',function(response, status, xhr){
//Target HTML is loaded, but not parsed by Angular


For complete clarity, I'm actually loading the angular content inside this call. The controller is inside the ajax content. See below.

<div class='ajax-loaded-content'>
<div ng-controller='MyNewCtrl'>
{{ this_should_be_compiled_but_isn't }}

I'm working on a 'legacy' project that doesn't use angular, and I'm trying to inject angular into it because that -- to me -- makes the most sense.


After receiving an HTML response via AJAX, use the $compile service to compile/link the template against some scope.

app.controller('TestCtrl', ['$scope', '$compile', '$element', '$http',
  function ($scope, $compile, $element, $http) {
    $http.get('dynamiclyDeterminedHTMLTarget').then(function (res) {
       // inject the DOM content

       // compile/link element contents

Alternatively, you can hand off the AJAX request to the ngInclude directive, which will take care of loading, compiling, linking, and injecting the content into the DOM.

<div ng-include="dynamicallyDeterminedHTMLTarget"></div>
<!-- (provided the scope has a "dynamicallyDeterminedHTMLTarget" property) -->

If you initiate the request outside of the Angular lifecycle, you can bootstrap the dynamic content as a stand-alone Angular app.

$('#target').load('dynamicallyDeterminedHTMLTarget', function() {
  angular.bootstrap(this, ['myApp']);