选中复选框时使用ng-model创建数组

use*_*392 28 angularjs angularjs-scope angularjs-ng-repeat

我是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 = {};
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

当我单击复选框时,上面的代码更新了playList,如下所示

{
    "http://test/test1.mp3": true,
    "http://test/test2.mp32": true,
    "http://test/test3.mp3": false
}
Run Code Online (Sandbox Code Playgroud)

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

预期:

[{
    name: "song1",
    url: "http://test/song1.mp3"
}, {
    name: "song2",
    url: "http://test/song2.mp3"
}]
Run Code Online (Sandbox Code Playgroud)

小智 45

你可以这样做:

$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});
}
Run Code Online (Sandbox Code Playgroud)

然后,在选择更改时简单调用selectedSongs():

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

在这里看演示