2017-08-25 63 views
1

据我所知,下面的代码应该使用不同的索引值每次渲染段落三次。相反,它只是渲染最后一个变形。这里发生了什么?

const app = angular.module('app', []) 
 
app.component('test', { 
 
    transclude: true, 
 
    controller: function($scope, $element, $transclude) { 
 
    //The transclusion should appear 3 times right? Since we're appending 3 times? 
 
    for(let index of [10, 11, 12]) { 
 
     const x = $transclude(Object.assign($scope.$new(true), {index})) 
 
     $element.append(x) 
 
    } 
 
    }, 
 
}); 
 
angular.bootstrap (document.querySelector('body'), ['app'])
<body> 
 
    <test> 
 
    <p>This is {{index}}</p> 
 
    </test> 
 
    <script src="https://code.angularjs.org/1.5.8/angular.js"></script> 
 
</body>

回答

1

$ transcludeFn接受接收与应用的新范围的元素的克隆中的第二参数。你想在这个函数中使用克隆放入dom中。你可以阅读更多关于它在这里:http://ng.malsup.com/#!/transclude-function或在这里:https://docs.angularjs.org/api/ng/service/$compile#-controller-

const app = angular.module('app', []) 
 
app.component('test', { 
 
    transclude: true, 
 
    controller: function($scope, $element, $transclude) { 
 
    //The transclusion should appear 3 times right? Since we're appending 3 times? 
 
    for(let index of [10, 11, 12]) { 
 
     $transclude(
 
     Object.assign($scope.$new(true), {index}), 
 
     x => $element.append(x) 
 
    ) 
 
    } 
 
    }, 
 
}); 
 
angular.bootstrap (document.querySelector('body'), ['app'])
<body> 
 
    <test> 
 
    <p>This is {{index}}</p> 
 
    </test> 
 
    <script src="https://code.angularjs.org/1.5.8/angular.js"></script> 
 
</body>