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"
}]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With