Vaibhav Chiruguri
Vaibhav Chiruguri

Reputation: 197

angularjs bind appended html to controller

Suppose initial html code is:

<div id="first" ng-controller="IndexPageController">

</div>

After the page is loaded, it makes some ajax request and appends new html

<div id="first" ng-controller="IndexPageController">
   <div id="appended">
      {{data}}
   </div>
</div>

My controller

MyApp.controller('IndexPageController', ['$scope', '$http',  function ($scope, $http) {
  $scope.data="something";
 });

Since the newly created DOM element does not inherit the $scope given to its compiled template. How can i bind the dom element to the controller?

Upvotes: 0

Views: 748

Answers (2)

Szabolcs D&#233;zsi
Szabolcs D&#233;zsi

Reputation: 8843

The $compile service can do just what you need.

Snippet:

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

app.controller("IndexPageController", function ($scope, $http, $compile, $timeout) {
    var htmlText = "<div id=\"appended\">" +
                   "{{data}}" +
                   "</div>";

    var linkFn = $compile(htmlText);
    var content = linkFn($scope);
    $("#first").append(content);
        
    $scope.data = "This should change after 5 seconds...";

    $timeout(function() {
        $scope.data = "Indeed, it is changed";
    }, 5000)
});

angular.bootstrap(document, ["app"]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.js"></script>

<div>
    <div id="first" ng-controller="IndexPageController">
    </div>
</div>

PS.: The resulting HTML will update properly. You can test it by injecting $timeout and adding the following piece of code:

$timeout(function() {
    $scope.data = "Indeed, it is changed";
}, 5000)

Upvotes: 1

Nijeesh
Nijeesh

Reputation: 847

You should use $compile to link the template and scope

Upvotes: 0

Related Questions