thank_you
thank_you

Reputation: 11107

Compile JS Directive after HTML loaded

So I'm wanting to compile a directive after the HTML is loaded.

var gifApp = angular.module('gifApp', []);

gifApp.directive('addition', function() {
  return function(scope, element) {
    element.html("<h1>" + scope.gif.name + "</h1>")

  }
});

function MainCtrl ($scope) {
  $scope.gif = {name: "Cat jumps on car"}

  $scope.push_code = function() {
    $("body").html("<div addition></div>")
  }
}

Whenever the function push_code is called the gif name is not displayed on the screen. Is it not possible to compile the code after the window is done loading with a directive? If it is possible, how do I fix this?

Upvotes: 1

Views: 306

Answers (1)

KayakDave
KayakDave

Reputation: 24676

You can add HTML after the window has loaded but Angular needs to know when you do. Right now since you're adding the div using jQuery Angular doesn't know the DOM has changed. And thus it doesn't get a chance to apply your directive to your new element.

The way I'd recommend dealing with this is using Angular's built-in version of jQuery called jQlite.

Here's a version of push_code() using jQlite:

push_code = function() {
   compiled = $compile('<div addition></div>')($scope);
   angular.element(document).find('body').append(compiled)
}

Here we create an Angular DOM element and tell Angular to $compile it on the current scope (which will apply your directive). Then we add that Angular element to the body in the jQlite equivalent of your jQuery approach.

Here's a demo: http://jsfiddle.net/Me2HW/3/

I put the push_code() call inside $timeout just to demonstrate there's no timing dependency here. You can make this call whenever you'd like, including well after the window has loaded, and it works.

Upvotes: 4

Related Questions