我有一個main directive
它有一個array
它的範圍包含數據構建其他directives
應編譯並附加到main directive
。從循環動態創建指令
問題是,當我遍歷該數組時,我只能從數組中的最後一個元素 獲取數據,因此我無法正確地爲每個自定義指令綁定相應的數據。
主要指令:
angular.module('testApp')
.directive('mainDirective', ["$compile", function ($compile) {
return {
template: ' <div><p>Main Directive </p><div class="insertion-point"></div></div>',
link: function (scope, element, attributes, controller) {
var insertionPoint = element.find('.insertion-point');
angular.forEach(scope.demoObj.panels, function (value, index) {
var directiveName = value.type;
scope.value = value;
var directiveString = "<div " + directiveName + " panel-data=value ></div>";
var compiledElement = $compile(directiveString)(scope);
insertionPoint.append(compiledElement);
});
}
}
}]);
指令被嵌套:
angular.module('testApp')
.directive('nestedDirective', [function() {
return {
scope:{
panelData:'='
},
template:' <div><p>Nested Directive </p>{{panelData.data.test}}</div>'
}
}]);
數據是這樣的:
$scope.demoObj = {
panels:[
{
id:'unique_id_1',
type:'nested-directive',
data:{
test:'test 1'
}
},
{
id:'unique_id_2',
type:'nested-directive',
data:{
test:'test 2'
}
},
{
id:'unique_id_3',
type:'nested-directive',
data:{
test:'test 3'
}
}
]
}
至於我可以在站立,編譯不會立即發生在forEach
語句中,這就是爲什麼每個指令都從編號爲unique_id_3
(數組中最後一個元素)的對象獲取數據的原因。而且所有的指令都有獨立的範圍。
編輯:據我所知,在的forEach我需要的價值增加的範圍,所以我可以把它pass
到嵌套指令隔離範圍,我的理解是,當環完成scope.value
將是循環的最後value
,但我的印象是,編譯將immediately
將值傳遞給嵌套的指令並完成它。
那麼,什麼時候編譯發生?
我該如何繞過這個限制?
有一件事:jqLite'find'僅限於標記名稱,所以你可能有一個問題與你的'插入點'。另外,數據對象中存在錯誤(例如缺少引號和不必要的分號)。僞代碼中的拼寫錯誤?或者他們在真實代碼中也存在問題? –
我有jQuery出現在頁面上。將元素附加到'main directive'不是一個問題。 –
你可以請設置一個[Plunker](http://plnkr.co/)來證明這個問題?我盡力爲您服務,但您提供的代碼存在太多問題。 –