Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating array with ng-model when checkbox selection

I am new to angularjs and want to create the model array when i click the checkbox and below is my code..

$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>

The above code updating the playList as shown below when i click the checkbox

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

But I want to create the ng-model in the below format, and remove the object when the checkbox is unchecked (for ex. if the uncheck the song3, the song3 object removed from the array). Can you tell me how can write this logic?

Expected:

[{
    name: "song1",
    url: "http://test/song1.mp3"
}, {
    name: "song2",
    url: "http://test/song2.mp3"
}]
like image 592
user845392 Avatar asked Jul 30 '13 15:07

user845392


1 Answers

You can do it like this:

$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()">

See demo here

like image 61
ehlers Avatar answered Nov 11 '22 03:11

ehlers