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">

    <script src=""></script>
    <script src=""></script>

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

                         function addTemplate2() {
                             var template = "FirstName : {{FirstName}}
LastName : {{LastName}}";
                         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();
                         angular.module('app', []).controller('ctrl', function ($scope) {
                             $scope.FirstName = "Musthaan";
                             $scope.LastName = "Majeed";
                         }).directive('testDir', function () {
                             return {
                                 template: "
<h1>From dir</h1>


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s