简体   繁体   中英

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?

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)

您应该使用$ compile链接模板和范围

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM