加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 复选框选择时,使用ng模型创建数组

发布时间:2020-12-17 08:26:20 所属栏目:安全 来源:网络整理
导读:我是新的角度,想要创建模型数组,当我点击复选框,下面是我的代码.. $scope.selectedAlbumSongs = [{ 'name': 'song1','url': 'http://test/song1.mp3'},{ 'name': 'song2','url': 'http://test/song2.mp3'},{ 'name': 'song3','url': 'http://test/song3.m
我是新的角度,想要创建模型数组,当我点击复选框,下面是我的代码..
$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模型,并且在复选框未被选中时删除该对象(例如,如果取消选中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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读