jeudi 27 août 2015

Check, uncheck items of checkbox in an array angularjs javascript

I have an array named namesData that I am showing on the UI. By default the checkboxes should be checked. When a checkbox is unchecked, that item should get removed from namesData. If the checkbox is checked, it should get added back to namesData.

$scope.namesData = [{"name":"abc.txt"}, {"name":"xyz.txt"}]

html:

<div ng-repeat="namesList in namesData">
        <input type="checkbox" ng-model="nameItem[$index].checked" ng-change="nameChange(namesList, nameItem[$index].checked, 'nameObj'+ $index, $index)" ng-checked="nameItem.checked" name="nameObj" id="{{'nameObj'+$index}}"/>&nbsp;
        <span>{{namesList.name}}</span>

Controller:

$scope.namesData = [{"name":"abc.txt"}, {"name":"xyz.txt"}];
$scope.nameItem.checked = true;

$scope.nameChange = function(list, isChecked, id, itemNum){
    if (isChecked){
        $scope.namesData.push(list);
    }
    else
        $scope.namesData.splice($scope.newNamesList.indexOf(list), 1);
};

Issue: The problem with the above logic is that the checked/unchecked items are getting added/removed to the end of the namesData array rather than its actual index item. Please advise how to resolve this.




Aucun commentaire:

Enregistrer un commentaire