如何以编程方式创建指令元素?

时间:2017-01-23 14:15:12

标签: angularjs angular-directive

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

这是我的傻瓜:http://plnkr.co/edit/XY6C6J70PjQTrjiwjHSz?p=preview

2 个答案:

答案 0 :(得分:3)

虽然指令的名称是&#34; anItem&#34;,但DOM元素被命名为&#34; an-item&#34;。这只是Angular命名约定。这有效:

document.createElement('an-item')

以下是更新后的Plunker

答案 1 :(得分:0)

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

scope.$applyAsync(function () {
    $compile(elm)(scope);
});
相关问题