我想在主体中添加一个div运行时,如下所示:
<div>{{test}}</div>
Run Code Online (Sandbox Code Playgroud)
它应该从Angular代码外部添加,例如单击按钮时.所以,没有指令,只是添加div.也许是简单的问题,但我无法在网上找到答案.
有
function TodoCtrl($scope) {
$scope.totalTodos = 4;
}
<body ng-app ng-controller="TodoCtrl">
<span>{{test}}</span> <!-- already works -->
</body>
Run Code Online (Sandbox Code Playgroud)
如果你真的需要从Angular之外添加HTML:
// HTML to add
var html = '<div>totalTodos: {{ totalTodos }}</div>';
// Add the HTML
var body = angular.element(document.querySelector('body'));
body.append(html);
// Get the application injector
// Can be retrieved from any element of the application wrapped in angular.element
var $injector = body.injector();
// Get a reference to the newly added HTML element
var divs = document.querySelectorAll('div');
var addedDiv = angular.element(divs[divs.length - 1]);
// Get the scope
var $scope = addedDiv.scope();
// Get the $compile service
var $compile = $injector.get('$compile');
// Compile the element and link it to the scope
$compile(addedDiv)($scope);
// Trigger the digest cycle
$scope.$apply();
Run Code Online (Sandbox Code Playgroud)
演示: http ://plnkr.co/edit/kNKNvEZsv1ChQejO90T6?p = preview
| 归档时间: |
|
| 查看次数: |
2157 次 |
| 最近记录: |