user3844782 user3844782 - 1 month ago 12
AngularJS Question

show checkbox elements of an array of checkboxes

I have got a set of radiobuttons and an array of checkboxes. When i click radiobutton1 it should load first checkbox element from the array and when i click radiobutton2 it should load remaining 3 checkbox elements from the array.But it shows all 4 checkboxes in both the cases. I tried like this.

In HTML

<form>
<label class="radio-inline" >
<input value="1" type="radio" ng-model="radioption" >RB1</label>
<label class="radio-inline">
<input value="2" type="radio" ng-model="radioption" >RB2</label>

<div class="">
<label ng-repeat="channel in channels | filter:myFilter" >
<input type="checkbox" name="selectedChannels[]" value="{{channel.value}}"
ng-model="channel.selected" >{{channel.name}}
</label></div>
</form>


In Controller

App.controller('ReportController', ['$scope', 'Report', function($scope, Report){
var self = this;
$scope.channels = [{ name: 'A', selected: false, value: '1',visible:false },
{ name: 'B', selected: false, value: '2' ,visible:false},
{ name: 'C', selected: false, value: '3' ,visible:false},
{ name: 'D', selected: false, value: '4' ,visible:false}
];
$scope.selection = [];

$scope.selectedChannels = function selectedChannels() {
return Report($scope.channels, { selected: true } );
};

$scope.$watch('channels|filter:{selected:true}', function (new) {
$scope.selection = new.map(function (channel) {
return channel.value;
});
}, true);

$scope.myFilter = function(){

if ($scope.radioption == '1'){

return $scope.channels[0].visible = true;
}
else if ($scope.radioption == '2'){

return [$scope.channels[1],{ visible: true },
$scope.channels[2],{ visible: true },
$scope.channels[3],{ visible: true }];
}
});
}]);

NTP NTP
Answer

I think you should approach this problem differently but if you want to use a filter try this

$scope.myFilter = function (channel) {
    if ($scope.radioption == 1) {
        if (channel.name == 'A') {
            return true;
        }
        else {
            return false;
        }
    }
    else if ($scope.radioption == 2) {

        if (channel.name == 'A') {
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return false;
    }
}

or you can add radioption column to channels array

$scope.channels = [{ name: 'A', selected: false, value: '1', radioption: 1 },
           { name: 'B', selected: false, value: '2', radioption: 2 },
           { name: 'C', selected: false, value: '3', radioption: 2 },
           { name: 'D', selected: false, value: '4', radioption: 2 }
];

and use ng-show

<input type="checkbox" ng-show="channel.radioption == radioption" name="selectedChannels[]" value="{{channel.value}}"
   ng-model="channel.selected">{{channel.name}}