2016-07-07 15 views
1

我不知道爲什麼ng-repeat會重複多次外部數組的長度。這是數組:angularjs:嵌套的ng-repeat被重複多次外部數組的長度

$scope.giornieventi = [{ 
    Intestazione: "Questa settimana", 
    Eventi: [{ 
      Nome: "Giacomo", 
      Immagine: "", 
      Url: "://www.....", 
      Data: "Oggi" 
     }, 
     { 
      Nome: "Giacomo2", 
      Immagine: "", 
      Url: "Ciao", 
      Data: "Domani" 
     }] 
}, 
{ 
    Intestazione: "Settimana successiva", 
    Eventi: [{ 
      Nome: "Roberto", 
      Immagine: "", 
      Url: "Ciao", 
      Data: "Oggi" 
     }, 
     { 
      Nome: "Roberto2", 
      Immagine: "", 
      Url: "Ciao", 
      Data: "Domani" 
     }] 
}]; 

這是NG-重複它不能正常工作:

<div ng-repeat="giorno in giornieventi"> 
    <h3 ng-show="alertData(giorno.Intestazione)">@{{ giorno.Intestazione }}</h3> 
    <article ng-repeat="evento in giorno.Eventi"> 
     @{{ evento.Nome }} 
    </article> 
</div> 

這是控制功能:

$scope.alertData= function(Intestazione) { 
    alert(Intestazione); return true; 
} 

奇怪的行爲是我得到警報4次而不是2次,我不知道爲什麼。

回答

1

你的代碼是好的,除了使用ng-show來獲得警報。 ng-show每次在範圍中的某些內容發生變化以確定是否應該顯示該元素時進行評估,因此您會看到所有事情都發生了兩次(因爲AngularJS評估了ng-show兩次)。

嘗試將其更改爲ng-init其上裝載元素時運行一次:

<div ng-repeat="giorno in giornieventi"> 
    <h3 ng-init="alertData(giorno.Intestazione)">@{{ giorno.Intestazione }}</h3> 
    <article ng-repeat="evento in giorno.Eventi"> 
     @{{ evento.Nome }} 
    </article> 
</div> 

這裏是工作提琴:http://jsfiddle.net/Lvc0u55v/6618/

+0

大,它的工作。但我在其他地方使用了ng-show,它只給出了兩個警報? –

+0

當你想決定是否顯示或隱藏一個元素時,你應該使用'ngShow',你不控制它運行的時間,Angular會。正如你所看到的,'

'元素按預期創建了兩次。你可以在這裏閱讀更多:https://docs.angularjs.org/api/ng/directive/ngShow – AlexD

+0

好的。這意味着它執行了4次,因爲髒檢查。 –