AngularJS : transclude ng-repeat inside directive

穿精又带淫゛_ 提交于 2020-01-04 11:04:09

问题


I have a directive that transcludes the original content, parses it, and uses the information in the original content to help build the new content. The gist of it looks like this:

.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
        }
    }
});

Then, I use it like this:

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

This all works fine like this. The problem occurs when I try to use an ng-repeat inside the directive content, like this:

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

When I try to do this, there are no items. Anyone know why this wouldn't work, or if there is a better way of accomplishing the same kind of thing?


回答1:


You may try:

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

For bit more details:

HTML:

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

Directive:

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);

You should let transcludFn know which scope you are going to use within transcludeFn. And if you don't want to use isolate scope, you may also try transcludeFn(scope.$parent....)



来源:https://stackoverflow.com/questions/25641618/angularjs-transclude-ng-repeat-inside-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!