source

확인란 선택 시 ng-model을 사용하여 배열 생성

nicesource 2023. 2. 10. 22:04
반응형

확인란 선택 시 ng-model을 사용하여 배열 생성

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>

체크박스를 클릭하면 아래와 같이 playList를 갱신하는 위 코드

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

단, 아래 형식으로 ng-model을 만들고 체크박스를 끄면 개체를 삭제합니다(예를 들어, 가 song3을 끄면 song3 개체가 배열에서 삭제됩니다).이 논리를 어떻게 쓸 수 있는지 말해줄 수 있나요?

예상:

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

다음과 같이 할 수 있습니다.

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

그런 다음 선택 내용이 변경되면 selected Songs()를 호출합니다.

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

데모를 참조해 주세요.

언급URL : https://stackoverflow.com/questions/17951756/creating-array-with-ng-model-when-checkbox-selection

반응형