5

I know I can apply to the template/templateURL, but currently the content will load from another place in my application.

JSbin: http://jsbin.com/imuseb/1/

HTML

<html ng-app="app">
  <head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>

  </head>
  <body>

    <div alert>here</div>

  </body>
</html>

JS code:

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

app.directive('alert', function (){
  return {
    link: function (scope, element, attrs) {
      element.on("click", function (){
        alert("here");
      });
    }
  };
});


$(function (){
   $("body").append("<div alert>here too</div>");
});
1
  • What did you try so far? Can you provide some sample code? Commented May 22, 2013 at 20:54

2 Answers 2

3

The new DOM must be accessible to the angular app in order to be compiled correctly. Here is one way to do this (not the only way). For applying the new DOM to the app's $rootScope, change this:

$(function (){
    $("body").append("<div alert>here too</div>");
});

to:

app.run(function($rootScope){
    $rootScope.$apply($("body").append("<div editable>here too</div>"));
});

According to the Angular docs:

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks sh0ber. I discovered that you can also use $compile... like this: $compile($("body").append("<div alert>here too</div>"))($scope);
What is the difference between using $apply and $compile in the context of the app.run() ? Thanks
0

It would be best if you could load your extra content from within the angular framework. Check out ng-include.

If that can't be used to do what you need, you'll have to manually call the angular compile service on the element, to compile it and link it onto the scope yourself using $compile.

Compiling elements touches the DOM, and therefore should be done within a custom directive if possible.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.