AngularJS我如何使用ng-repeat编译一个元素?

时间:2014-05-08 03:33:23

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-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";
        }
      };
    }
  };
});

我做错了什么?

1 个答案:

答案 0 :(得分:3)

你不需要调用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);