I am trying to solve a serious problem that I am encountering with angularJS regarding the use of dynamically added html containing ng-controller
.
Suppose I want to add a div to the DOM, which is ng-controller
what silences the data on the screen. I can achieve this as follows:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
var demoData = {
'test1': 'one',
'test2': 'two'
};
var myApp = angular.module('myApp', []);
myApp.controller('TestCtrl', function ($scope) {
$scope.demo = demoData;
});
</script>
</head>
<body>
<div ng-controller="TestCtrl">
{{demo}}
</div>
</body>
</html>
which outputs the following as expected:
{"test1": "one", "test2": "two"}
However, now let's say that the div should actually load dynamically, possibly when the user clicks the button. In this case, I would replace the tag in the above example as follows:
<body>
<button onclick="addDiv();">Click to add Div!</button>
<script>
function addDiv() {
var newDiv = $('<div ng-controller="TestCtrl">{{demo}}</div>');
$(document.body).append(newDiv);
}
</script>
</body>
which outputs the following when I click the button:
Click to add a Div!
{{Demo}}
; angular DOM, . .
, AngularJS, , , , :
angular Angular. , , . , (), JQuery/jqLite . . Angular..
, , .
HTML, ng-controller JQuery. AngularJS. var $div = $('{{content.label}}'); $ (Document.body).append($ );
angular.element(document).injector().invoke(function($compile) {
var scope = angular.element($div).scope();
$compile($div)(scope);
});
, , addDiv()
:
function addDiv() {
var $newDiv = $('<div ng-controller="TestCtrl">{{demo}}</div>');
$(document.body).append($newDiv);
angular.element(document).injector().invoke(function ($compile) {
var scope = angular.element($newDiv).scope();
$compile($newDiv)(scope);
});
}
, , ?
. :
, Div!
{{}}
![sad panda is sad](https://fooobar.com/undefined)
, , Google , , !