Skip to content

Instantly share code, notes, and snippets.

@umidjons
Created August 12, 2014 05:14
Show Gist options
  • Save umidjons/1fb8ae674df4c71f85cf to your computer and use it in GitHub Desktop.
Save umidjons/1fb8ae674df4c71f85cf to your computer and use it in GitHub Desktop.

Revisions

  1. umidjons revised this gist Aug 12, 2014. 1 changed file with 18 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions angular-compile-dynamic-html.md
    Original file line number Diff line number Diff line change
    @@ -31,4 +31,22 @@ angular directives.
    </script>
    </body>
    </html>
    ```

    We can get reference to `$compile` outside of angular via `injector().invoke()`.

    ```javascript
    jQuery(document).ready(function($){
    $('.foo').on('click',function(e){
    e.preventDefault();
    angular.element(document).injector().invoke(function($compile){
    var obj=$('[obj]'); // get wrapper
    var scope=obj.scope(); // get scope
    // generate dynamic content
    obj.html($('<input type="text" ng-pattern="/^([0-9]+)$/" ng-model="test"><span>{{test}}</span>'));
    // compile!!!
    $compile(obj.contents())(scope);
    });
    });
    });
    ```
  2. umidjons created this gist Aug 12, 2014.
    34 changes: 34 additions & 0 deletions angular-compile-dynamic-html.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    Compile dynamic template from outside of angular
    ===

    I want to load dynamic HTML content via AJAX, then compile it, because it contains
    angular directives.

    ```html
    <!DOCTYPE html>
    <html ng-app="app">
    <head>
    <title>Compile dynamic HTML</title>
    <script type="text/javascript" src="js/jquery-1.11.0.js"></script>
    <script type="text/javascript" src="js/angular.js"></script>
    </head>
    <body ng-controller="TestCtrl">

    <div obj></div>

    <button class="foo">Change</button>

    <script type="text/javascript">
    var app=angular.module('app',[]);
    app.controller('TestCtrl',function($scope){});
    jQuery(document).ready(function($){
    $('.foo').on('click',function(e){
    // todo: load HTML content via AJAX or generate via jQuery
    // todo: compile new HTML content, which contains Angular directives
    });
    });
    </script>
    </body>
    </html>
    ```