srgbnd
srgbnd

Reputation: 5614

How to create directives elements programmatically?

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

Answers (2)

MeTe-30
MeTe-30

Reputation: 2542

var elm = angular.element('<an-item"></an-item>');
container.append(elm);

scope.$applyAsync(function () {
    $compile(elm)(scope);
});

Upvotes: 0

lex82
lex82

Reputation: 11307

While the name of the directive is "anItem", the DOM elements are named "an-item". This is just the Angular naming convention. This works:

document.createElement('an-item')

Here is the updated Plunker.

Upvotes: 3

Related Questions