【问题标题】:How to create directives elements programmatically?如何以编程方式创建指令元素?
【发布时间】:2017-06-08 02:00:33
【问题描述】:

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

【问题讨论】:

  • 你不能在你的 html 中使用 ng-if 吗?并在您的控制器中设置一个标志是否渲染?
  • 只是大小写问题:document.createElement('an-item') 而不是anItem
  • @lex82 你是对的,谢谢!发表你的答案,我会给它评分。

标签: angularjs angular-directive


【解决方案1】:

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

document.createElement('an-item')

这是更新后的Plunker

【讨论】:

    【解决方案2】:
    var elm = angular.element('<an-item"></an-item>');
    container.append(elm);
    
    scope.$applyAsync(function () {
        $compile(elm)(scope);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2011-07-05
      • 2015-12-28
      • 1970-01-01
      相关资源
      最近更新 更多