Search code examples
angularjsangular-directive

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


Solution

  • 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.