如何以编程方式创建指令元素?
How to create directives elements programmatically?
Angular 1.4.8
如何在控制器中以编程方式创建指令元素?我试过 $compile 但它对我不起作用。
控制器和指令
angular.module('plunker', [])
.controller('MainCtrl', function ($scope, $compile) {
var container = angular.element(document.getElementById('container'));
$scope.user = {item: 'Axe'};
var item = angular.element(document.createElement('anItem'));
item = $compile(item)($scope);
container.append(item);
})
.directive('anItem', function(){
return {
templateUrl: 'template.html'
};
});
template.html
<p>Item: {{user.item}}</p>
index.html
...
<body ng-controller="MainCtrl">
<div id="container"></div>
</body>
...
虽然指令的名称是 "anItem",但 DOM 元素被命名为 "an-item"。这只是 Angular 命名约定。这有效:
document.createElement('an-item')
这是更新后的 Plunker。
var elm = angular.element('<an-item"></an-item>');
container.append(elm);
scope.$applyAsync(function () {
$compile(elm)(scope);
});
Angular 1.4.8
如何在控制器中以编程方式创建指令元素?我试过 $compile 但它对我不起作用。
控制器和指令
angular.module('plunker', [])
.controller('MainCtrl', function ($scope, $compile) {
var container = angular.element(document.getElementById('container'));
$scope.user = {item: 'Axe'};
var item = angular.element(document.createElement('anItem'));
item = $compile(item)($scope);
container.append(item);
})
.directive('anItem', function(){
return {
templateUrl: 'template.html'
};
});
template.html
<p>Item: {{user.item}}</p>
index.html
...
<body ng-controller="MainCtrl">
<div id="container"></div>
</body>
...
虽然指令的名称是 "anItem",但 DOM 元素被命名为 "an-item"。这只是 Angular 命名约定。这有效:
document.createElement('an-item')
这是更新后的 Plunker。
var elm = angular.element('<an-item"></an-item>');
container.append(elm);
scope.$applyAsync(function () {
$compile(elm)(scope);
});