I'll appreciate any help. My problem: I can't show value from $scope.info
in my view. I don't have direct access to html, so I can change DOM only via js. I created new element and added it to the DOM with append()
method
我会感激任何帮助。我的问题:在我看来,我无法从$ scope.info中显示价值。我没有直接访问html,所以我只能通过js更改DOM。我创建了新元素并使用append()方法将其添加到DOM中
$scope.info = {
clicks: 15862,
spent: '$124',
created: '04/08/2017',
author: 'John Kovalenko',
name: 'Advertise US'
};
var info = document.createElement('div');
info = angular.element(info).attr({
'ng-bind': 'info',
'class': 'statistic-info'
});
angular.element(infoContainer).append(info[0]);
I created example here. http://jsfiddle.net/ADukg/13598/
我在这里创建了例子。 http://jsfiddle.net/ADukg/13598/
What I'm doing wrong? Thank you
我做错了什么?谢谢
2 个解决方案
#1
4
You have to use $compile
when you manually inject anything that uses directives
手动注入任何使用指令的东西时,必须使用$ compile
var info = angular.element('<div>').attr({
'ng-bind': 'info.author',
'class': 'statistic-info'
});
info = $compile(info)($scope);
angular.element(infoContainer).append(info);
Be sure to inject $compile
wherever you use it
一定要在任何地方注入$ compile
DEMO
#2
2
The simplest answer is to add the data into the HTML content before appending it. Since you have an object, I've supplied one of it's properties in the snippet below.
最简单的答案是在附加数据之前将数据添加到HTML内容中。由于你有一个对象,我在下面的代码片段中提供了它的一个属性。
What is happening is your page loads, and the digest cycle has already completed. What you are appending is simply plain text, and therefor is not interpolated. This method that I am providing will not provide two-way binding. If that is required, you should be using a directive.
发生的事情是您的页面加载,摘要周期已经完成。你要附加的只是纯文本,因此不进行插值。我提供的这种方法不会提供双向绑定。如果需要,您应该使用指令。
var infoTwo = '<div><p>' + $scope.info.clicks + '</p></div>';
That said, charlieftl has the best answer.
也就是说,charlieftl有最好的答案。
#1
4
You have to use $compile
when you manually inject anything that uses directives
手动注入任何使用指令的东西时,必须使用$ compile
var info = angular.element('<div>').attr({
'ng-bind': 'info.author',
'class': 'statistic-info'
});
info = $compile(info)($scope);
angular.element(infoContainer).append(info);
Be sure to inject $compile
wherever you use it
一定要在任何地方注入$ compile
DEMO
#2
2
The simplest answer is to add the data into the HTML content before appending it. Since you have an object, I've supplied one of it's properties in the snippet below.
最简单的答案是在附加数据之前将数据添加到HTML内容中。由于你有一个对象,我在下面的代码片段中提供了它的一个属性。
What is happening is your page loads, and the digest cycle has already completed. What you are appending is simply plain text, and therefor is not interpolated. This method that I am providing will not provide two-way binding. If that is required, you should be using a directive.
发生的事情是您的页面加载,摘要周期已经完成。你要附加的只是纯文本,因此不进行插值。我提供的这种方法不会提供双向绑定。如果需要,您应该使用指令。
var infoTwo = '<div><p>' + $scope.info.clicks + '</p></div>';
That said, charlieftl has the best answer.
也就是说,charlieftl有最好的答案。