Reputation: 5614
Angular 1.4.8
How can I create directive elements programmatically inside a controller? I tried $compile but it doesn't work for me.
Controller and directive
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>
...
Here is my plunker: http://plnkr.co/edit/XY6C6J70PjQTrjiwjHSz?p=preview
Upvotes: 3
Views: 1134
Reputation: 2542
var elm = angular.element('<an-item"></an-item>');
container.append(elm);
scope.$applyAsync(function () {
$compile(elm)(scope);
});
Upvotes: 0