2

我有一條指令,該指令跨越原始內容,解析它,並使用原始內容中的信息來幫助構建新內容。它的要點如下:AngularJS:transclude ng-repeat內部指令

.directive('list', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     templateUrl: '...', 
     scope: true, 
     controller: function($scope, $element, $attrs, $transclude) { 
      var items; 
      $transclude(function(clone) { 
       clone = Array.prototype.slice.call(clone); 
       items = clone 
        .filter(function(node) { 
         return node.nodeType === 1; 
        }) 
        .map(function(node) { 
         return { 
          value: node.getAttribute('value') 
          text: node.innerHTML 
         }; 
        }); 
      }); 

      // Do some stuff down here with the item information 
     } 
    } 
}); 

然後,我用這樣的:

<list> 
    <item value="foo">bar</item> 
    <item value="baz">qux</item> 
</list> 

這一切工作正常這樣。

<list> 
    <item ng-repeat="item in items" value="{{ item.value }}">{{ item.text }}</item> 
</list> 

當我嘗試這樣做,有沒有項目:當我嘗試使用ng-repeat指令裏面的內容,這樣會出現問題。任何人都知道爲什麼這不起作用,或者有更好的方法來完成同樣的事情?

+1

這看起來像它可以解決你的問題。 [http://stackoverflow.com/questions/14388247/ng-repeat-with-ng-transclude-inside-a-directive][1] [1]:HTTP:// stackoverflow.com/questions/14388247/ng-repeat-with-ng-transclude-inside-a-directive – jim0thy 2014-09-03 10:13:18

+0

有趣的是,我會試試看。 – kbjr 2014-09-03 10:14:54

回答

2

你可以試試:

transcludeFn(scope, function (clone) { 
    iElem.append(clone); 
}) 

對位的詳細信息:

HTML:

<foo data-lists='[lists data here]'> 
<li ng-repeat="list in lists">{{list.name}}</li> 
</foo> 

指令:

var Foo = function() { 
    return { 
    restrict: 'E', 
    template: '...' 
    transclude: true, 
    scope: { lists: '=?' } 
    link: function(scope, iElem, iAttrs, Ctrl, transcludeFn) { 
      transcludeFn(scope, function (clone) { 
       iElem.append(clone); 
      } 
    } 
    }; 
}; 

.directive('foo', Foo); 

你應該讓transcludFn知道哪些範圍你是g在transcludeFn內使用。如果你不想使用隔離示波器,你也可以嘗試transcludeFn(scope.$parent....)