user845392 user845392 - 1 year ago 171
AngularJS Question

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


<fieldset data-role="controlgroup">
<legend>Select songs to play</legend>
<label ng-repeat="song in selectedAlbumSongs">
<input type="checkbox" name="{{song.url}}" id="{{}}" ng-model="playList[song.url]">
<label for="{{}}">{{}}</label>

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?


name: "song1",
url: "http://test/song1.mp3"
}, {
name: "song2",
url: "http://test/song2.mp3"

Answer Source

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="{{}}" ng-model="song.checked" ng-change="selectedSongs()">

See demo here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download