2013-07-30 14 views
28

Ben angularjs için yeni ve benim kodudur altındaki onay kutusunu tıklayın ve ne zaman modeli dizisi oluşturmak istiyorum ..oluşturma dizisi ne zaman onay kutusu seçimi

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

Playlist güncellenmesi yukarıdaki kod i kutusunu

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

tıkladığınızda aşağıda gösterildiği Ama ben ng-modunu oluşturmak istiyorum Aşağıdaki biçimde l yazın ve onay kutusu işaretlenmediğinde nesneyi kaldırın (ör. eğer song3'ün işaretini kaldırırsanız, song3 nesnesi diziden kaldırılır). Bu mantığı nasıl yazabileceğimi söyler misin?

Beklenen:

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

cevap

45

Böyle yapabilirsiniz:

$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}); 
} 

Sonra basit çağrı selectedSongs() seçimi değiştirildiğinde:

<input type="checkbox" name="{{song.url}}" id="{{song.name}}" ng-model="song.checked" ng-change="selectedSongs()"> 

Bkz demo here

+1

Merhaba @ehlers mükemmel bir çözümdür. Bir ngRepeat içinde onay kutuları için dinamik ngModels olduğunda aynı düşünceyi nasıl yapabileceğimi söyleyebilir misiniz? Örneğin, her bir onay kutusu için ngmodel olarak bir 'song.id' olan bir durum söz konusu olduğunda:' '. Yukarıdaki kodun yalnızca ng-model = "song.checked" 'durumunda çalışırken çalıştığını fark ettim. Ama dinamik bir ngmodel '' song.id '' olduğunda, işe yaramıyor. Bu durumda herhangi bir geçici çözüm plz? – Neel