Reputation: 114
I created a new (the second div) html element dynamically by the following code:
var body = document.getElementsByTagName('body')[0];
var container = document.createElement('div');
var node = document.createTextNode('Hello, {{ name }}');
container.appendChild(node);
body.appendChild(container);
Add, my index.html like this:
<html ng-app>
<body>
<div>
Hello, {{ name }}
</div>
</body>
</html>
Well, the first Hello, {{name}}
works well, it shows Hello,World
. but the second one Hello, {{name}}
, just shows <div>Hello, {{name}}</div>
, How can I let the angular to know I have create a new element, and let it to explain the value?
Upvotes: 1
Views: 156
Reputation: 11985
The correct way to do this is to use the $compile service.
From plunk: http://plnkr.co/edit/zijB2HM8OSblvmuu1jn9?p=preview
app.controller('MainCtrl', function($scope, $compile, $document) {
$scope.name = 'World';
var d;
$scope.add = function() {
var document = $document[0];
var node = document.createTextNode('Hello Sweet {{name}}');
var el = $compile(node)($scope);
if(!d) {
d = $document.find('div');
}
console.log('l=',d.length);
d.append(el);
};
});
Upvotes: 2
Reputation: 2937
I can suggest to you the following answer which is more in the idea of angularjs. In the JS side, create an array which the names that you want to display and if you want to add a new functio updating your data.
In the HTML side, just use the ng-repeat
directive to print your names.
<html ng-app='myapp'>
<body>
<div ng-controller='ctrl'>
<ul ng-repeat="name in names">
<li> Hello {{name}} </li>
</ul>
</div>
</body>
</html>
<script>
var app = angular.module('myapp',[]);
app.controller('ctrl', function($scope) {
$scope.names = ["foo","bar"];
});
</script>
Also, I give the jsfiddle -> https://jsfiddle.net/xjtmp27u/
Upvotes: 0
Reputation: 952
This is due to lazy load of angular. Instead of directly binding the modal you can call a function
var body = document.getElementsByTagName('body')[0];
var container = document.createElement('div');
var node = document.createTextNode('Hello, {{ myFoo()}}');
container.appendChild(node);
body.appendChild(container);
and in your controller define myFoo like this
$scope.myFoo = function(){
return "My Custom Text";
}
Upvotes: 0