【问题标题】:Creating array with ng-model when checkbox selection选择复选框时使用 ng-model 创建数组
【发布时间】:2013-07-30 15:54:29
【问题描述】:

我是 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"
}]

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    你可以这样做:

    $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});
    }
    

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

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

    查看演示here

    【讨论】:

    • 嗨@ehlers,这是一个很好的解决方案。当我在 ngRepeat 中有用于复选框的动态 ngModels 时,你能告诉我如何做同样的想法吗?例如,在这种情况下,我有一个 song.id 作为每个复选框的 ngmodel:&lt;input type="checkbox" name="{{song.url}}" id="{{song.name}}" ng-model="song.id" ng-change="selectedSongs()"&gt;。我注意到上面的代码只有在拥有ng-model="song.checked" 时才有效。但是当我有一个动态 ngmodel "song.id" 时,它就不起作用了。在这种情况下有什么解决方法吗?
    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 2017-08-22
    • 2020-07-05
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    相关资源
    最近更新 更多