2013-07-30 5 views
28

私はangularjsに新しいですし、私は私のコードがある以下のチェックボックスをクリックしたときにモデル配列を作成したい。..作成配列するとき、チェックボックスの選択

$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を以下の形式で入力し、チェックボックスがオフの場合はオブジェクトを削除します(ex。ソング3のチェックを外すと、ソング3オブジェクトがアレイから削除されます)。この論理をどのように書くことができるか教えてください。

予想:

[{ 
    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を持っているときに、同じことをどうやって行うことができるか教えていただけますか?たとえば、次のような場合、各チェックボックスのngmodelとして 'song.id'があります:' '私は上記のコードが 'ng-model =" song.checked "'を持つときにのみ動作することに気付きました。しかし、私が動的なngmodel '' song.id "'を持っていると、動かない。その場合の回避策はどれですか? – Neel

関連する問題