0

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

7 Comments

If i change $scope.data , Will it update in appended html?
As you can see, $scope.data is changed after being appended in the snippet and it shows up properly in the resulting HTML. Updated the answer.
will it make a difference if i dont use append fucntion and just extract html from compiled dom element like this content[0].outerHTML and use this html to append later.
The way you're adding the value returned by the link function (content in this specific example) to the DOM doesn't matter as far as I know. I just used the jQuery append function with a HTML string, because that was the first thing that came to mind.
jsfiddle i have made a fiddle. why ng-click is not binding to the controller scope?
|
0

You should use $compile to link the template and scope

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.