1

In the AngularJS docs, for $compile it states:

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

https://docs.angularjs.org/api/ng/service/$compile

I still can't figure out WHEN you would use this. The docs tell you the details on all the API methods and properties but fails to clearly indicate why and when you'd want to use this.

scniro
  • 16,844
  • 8
  • 62
  • 106
Johann
  • 27,536
  • 39
  • 165
  • 279
  • When you create and append HTML dynamically to the DOM and it contains directives, you would call $compile to activate the directives. Otherwise, if you don't, it'll just be dead HTML with none of the directive behaviour. – Michael Kang Jul 07 '14 at 09:44
  • This is Good explaination given by Scott Allen as to why we use $Compile http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx – sam rodrigues Jul 07 '14 at 09:54
  • @pixelbits Can you think of a real world example where you would have directives embedded in HTML that needs to then be compiled? – Johann Jul 07 '14 at 10:04
  • 1
    An angular-based HTML editor. The user enters HTML in their favorite WYSIWYG editor and submits it for posting. If it contains directives, then you'll want to compile and link it before posting. – Michael Kang Jul 07 '14 at 10:10
  • One real world example I've encountered: if you have recursive directives then you will need to manually `$compile` the templates to avoid an infinite compile loop: http://stackoverflow.com/questions/18173995/recursive-custom-directives-using-ngrepeat?rq=1 – Sly_cardinal Jul 07 '14 at 10:11
  • Personally, I think one should avoid manual compilation. There are usually more 'Angular' ways to do it declaratively using templates. – Michael Kang Jul 07 '14 at 10:15

0 Answers0