30

我是 angularjs 的新手,想在单击复选框时创建模型数组,下面是我的代码..

$scope.selectedAlbumSongs = [{
    'name': 'song1',
        'url': 'http://test/song1.mp3'
}, {
    'name': 'song2',
        'url': 'http://test/song2.mp3'
}, {
    'name': 'song3',
        'url': 'http://test/song3.mp3'
}];
$scope.playList = {};

HTML:

<fieldset data-role="controlgroup">
    <legend>Select songs to play</legend>
    <label ng-repeat="song in selectedAlbumSongs">
        <input type="checkbox" name="{{song.url}}" id="{{song.name}}" ng-model="playList[song.url]">
        <label for="{{song.name}}">{{song.name}}</label>
    </label>
</fieldset>

当我单击复选框时,上面的代码更新播放列表如下所示

{
    "http://test/test1.mp3": true,
    "http://test/test2.mp32": true,
    "http://test/test3.mp3": false
}

但我想以以下格式创建 ng-model,并在未选中复选框时删除对象(例如,如果取消选中 song3,则从数组中删除 song3 对象)。你能告诉我怎么写这个逻辑吗?

预期的:

[{
    name: "song1",
    url: "http://test/song1.mp3"
}, {
    name: "song2",
    url: "http://test/song2.mp3"
}]
4

1 回答 1

47

你可以这样做:

$scope.selectedAlbumSongs = [ { 'name': 'song1', 'url': 'http://test/song1.mp3' }, { 'name': 'song2', 'url': 'http://test/song2.mp3' }, {'name': 'song3', 'url': 'http://test/song3.mp3' }];

$scope.selectedSongs = function () {
    $scope.playList = $filter('filter')($scope.selectedAlbumSongs, {checked: true});
}

Then, simple call selectedSongs() when the selection is changed:

<input type="checkbox" name="{{song.url}}" id="{{song.name}}" ng-model="song.checked" ng-change="selectedSongs()">

在此处查看演示

于 2013-07-30T16:08:25.017 回答