我试图弄清楚为什么我的复选框列表(来自ng-repeat =" myCtrl.genreSelected"中的歌曲)没有正确显示
我有一些收音机,您可以从中选择以下三种音乐类型之一:
<input type="radio" name="genre" ng-value="myCtrl.rockSongs" ng-model="myCtrl.genreSelected"> Rock
<input type="radio" name="genre" ng-value="myCtrl.rapSongs" ng-model="myCtrl.genreSelected"> Pop
<input type="radio" name="genre" ng-value="myCtrl.popSongs" ng-model="myCtrl.genreSelected"> Rap
我想要选择哪个收音机来创建一个带有这些歌曲名称的复选框列表:
<input type="checkbox" name="song" ng-repeat="song in myCtrl.genreSelected" ng-checked={{song.checked}}>{{song.song}}
以下是每种类型的控制器中的歌曲:
this.rockSongs = [{song: "Rock song #1", checked: true},
{song: "Rock song #2", checked: false},
{song: "Rock song #3", checked: false},
{song: "Rock song #4", checked: false},
{song: "Rock song #5", checked: false}];
this.rapSongs = [{song: "Rap song #1", checked: false},
{song: "Rap song #2", checked: false},
{song: "Rap song #3", checked: false},
{song: "Rap song #4", checked: false},
{song: "Rap song #5", checked: false}];
this.popSongs = [{song: "Pop song #1", checked: false},
{song: "Pop song #2", checked: false},
{song: "Pop song #3", checked: false},
{song: "Pop song #4", checked: false},
{song: "Pop song #5", checked: false}];
现在我有摇滚歌曲出现在载入中:
this.genreSelected = this.rockSongs;
现在,如果选中,则会从ng-repeat中显示复选框列表并选中检查:true。但是这首歌的名字并没有出现在{{song.song}}
的地方答案 0 :(得分:3)
ngRepeat指令仅重复其元素,因此您的{{song.song}}
绑定实际上在ngRepeat之外。
您必须将输入和绑定包装在另一个元素中,然后重复该操作
<div ng-repeat="song in myCtrl.genreSelected">
<input type="checkbox" name="song" ng-checked="song.checked"> {{song.song}}
</div>
或使用双向绑定使用ngModel:
<div ng-repeat="song in myCtrl.genreSelected">
<input type="checkbox" name="song" ng-model="song.checked"> {{song.song}}
</div>
答案 1 :(得分:1)
需要进行两项更改。首先,使用ng-model而不是ng-checked。其次,为了查看歌曲名称,您需要将输入包装在div中并将ng-repeat移动到div。
<div ng-repeat="song in myCtrl.genreSelected">
<input type="checkbox" name="song" ng-model='song.checked'>{{song.song}}
</div>