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

标签 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 = {};

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

最佳答案

你可以这样做:

$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

关于angularjs - 选择复选框时使用 ng-model 创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17951756/

相关文章:

angularjs - 为什么 Scope.$apply() 调用 $rootScope.$digest() 而不是 this.$digest()?

javascript - angularjs 应用过滤器交叉嵌套指令(过滤器也适用于 child ,即使它与 parent 不匹配)?

javascript - :AngularJS: ng-selected is not working with a true statement

javascript - 如何从 AngularJS 中的对象数组构建带有 rowspan 的表

angularjs - 如何在 Angular 中的服务和工厂中定义构造函数?

javascript - Bootstrap 内容的 Angular 路由

angularjs - 为什么无法通过 id 选择 'track by' 的 Angular ng-options

javascript - 动态 AngularJS 指令

angularjs - 带有谓词函数的 Angular ng-repeat 过滤器无法按预期工作

javascript - 比较两个数组的 Angular 并对其进行循环