Bind angular scope to dynamically added html

angularSome times we need to integrate html contents to our angular application. some times we create contents from jQuery and integrate it to our application. like kendo UI in jQuery style, jQuery dataTables etc.
At that time the following snippet will useful.

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
</head>

<body ng-app="app">
<div ng-controller="ctrl" id="dvController">
        <test-dir></test-dir>
        <button onclick="addTemplate1()">Add template 1</button>
        <button onclick="addTemplate2()">Add template 2</button>
<div id="dvContainer"></div>
</div>
<script>
                         function addTemplate1() {
                             var template = "<test-dir></test-dir>";
                             $("#dvContainer").html(template);
                             bindAngular();
                         }

                         function addTemplate2() {
                             var template = "FirstName : {{FirstName}}
LastName : {{LastName}}";
                             $("#dvContainer").html(template);
                             bindAngular();
                         }
                         function bindAngular() {
                             var $controllerElement = angular.element('#dvController');
                             var $appElement = angular.element('body');

                             // compiling and applying / digesting the scope.
                             $appElement.injector().invoke(function ($compile) {
                                 var scope = $controllerElement.scope();
                                 $compile($controllerElement)(scope);
                                 scope.$apply();
                             });
                         }
                         angular.module('app', []).controller('ctrl', function ($scope) {
                             $scope.FirstName = "Musthaan";
                             $scope.LastName = "Majeed";
                         }).directive('testDir', function () {
                             return {
                                 template: "
<h1>From dir</h1>
"
                             };
                         })
    </script>
</body>

</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s