簡體   English   中英

AngularJS我如何使用ng-repeat編譯一個元素?

[英]AngularJS how do I $compile an element with an ng-repeat?

我似乎無法想出這個。 我需要使用$ compile(我認為),用范圍連接一個元素。 這適用於沒有其他指令(特別是ng-repeat)的元素..但不適用於具有ng-repeat的元素。 我想出了一個例子:

Plunkr: http ://plnkr.co/edit/Nmn7n631iijP1lQAZaXv?p =preview

var count = 0;
angular.module("dir", [])

.controller("main", function($scope) {
  $scope.test = 1;
})

.directive('ngHello', function($compile) {
  return {
    scope: true,
    compile: function(telem, attrs, transclude) {
      var repeat = "<div>"+
      "<div ng-repeat='item in items'>{{item}}</div>"+
      "</div>";
      var r = angular.element(repeat);
      telem.after(r);

      var easy = "<div>this is {{test2}}</div>";
      var e = angular.element(easy);
      telem.after(e);


      return {
        pre: function(scope, ielem, iAttrs, controller) {
          $compile(r)(scope); //why doesn't this seem to work?
          $compile(e)(scope);
        },
        post: function(scope, ielem, iAttrs, controller) {
          scope.items = [];
          for(var i=0; i<5; i++) {
            scope.items.push(count++);
          }
          scope.test2 = "test4";
        }
      };
    }
  };
});

我究竟做錯了什么?

你不需要調用angular.element,$ compile將需要html。 你甚至不需要使用指令的編譯功能,這可以在鏈接功能中完成。 $ compile返回已編譯的元素。 您需要將其用作要添加的元素。

來自plunkr的相關位:

.directive('ngHello', function($compile) {
  var repeat = "<div>"+
  "<div ng-repeat='item in items'>{{item}}</div>"+
  "</div>";
  var r = angular.element(repeat);
  return {
    scope: true,
    link: function(scope, elem, attrs) {
      scope.items = [];
      scope.items.push(1);
      scope.items.push(2);
      scope.items.push(3);
      var e = $compile(repeat)(scope);
      elem.after(e);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM