2013-07-30 36 views
28

我是新來angularjs和要創建的模型排列當我點擊複選框,下面是我的代碼..與NG-模型創建數組時複選框選擇

$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模式l以下面的格式,並且當取消選中複選框時刪除對象(例如,如果取消選中song3,則從數組中刪除song3對象)。你能告訴我怎麼寫這個邏輯?

預計:

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

回答

45

你可以這樣說:

$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

+1

嗨@ehlers是一個很好的解決方案。你能告訴我如何在ngRepeat中的動態ngModels複選框時做同樣的事情嗎?例如,在這種情況下,我爲每個複選框使用'song.id'作爲ngmodel:''。我注意到上面的代碼只有在'ng-model =「song.checked」'時纔有效。但是當我有一個動態ngmodel''song.id''時,它不起作用。在這種情況下任何解決方法plz? – Neel