如何以编程方式创建指令元素?
问题描述:
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>
...
他re是我的翻牌:http://plnkr.co/edit/XY6C6J70PjQTrjiwjHSz?p=preview
答
虽然指令的名称是“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);
});
你不能使用ng-if在你的html中吗?并在你的控制器上设置一个标志来渲染或不渲染它? –
这只是一个套管问题:'document.createElement('an-item')'而不是'anItem' – lex82
@ lex82你是对的,谢谢!发布您的答案,我会评分它。 – trex