2017-08-25 64 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>