developer developer - 4 months ago 14
AngularJS Question

Angularjs - Simple radio button NOT able select

I am trying to show a dynamic list (of file name items) using an html radio button. Please find the code below for the same:

<html>
<head>
<script src="angular-v1.5.5.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<label>
<input type="radio" ng-model="inputCreatedBy" value="byX" ng-value="true"
ng-click="toggleSelection('byX')"> by X&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" ng-model="inputCreatedBy" value="byAll" ng-value="false"
ng-click="toggleSelection('byAll')"> by All&nbsp;&nbsp;&nbsp;&nbsp;
</label>
<br/><br/>
<label ng-repeat="file in displayFiles">
{{ file.name }}
</label>

</div>
</body>
<script>
var app = angular.module("myApp",[]);
app.controller('myCtrl', function ($scope, filterFilter) {
$scope.files = [
{ name: 'file1', createdBy: 'X' },
{ name: 'file2', createdBy: 'X' },
{ name: 'file3', createdBy: 'Y' },
{ name: 'file4', createdBy: 'Y' }
];
$scope.displayFiles = [];
$scope.toggleSelection = function(selectionType) {
if(selectionType == 'byX') {
for(i=0;i<$scope.files.length;i++) {
if($scope.files[i].createdBy =='X') {
$scope.displayFiles.push($scope.files[i]);
}
}
} else if(selectionType == 'byAll') {
$scope.displayFiles = $scope.files;
}
};
});
</script>
</html>


I am facing the below issues with this code:

(1) The Radio button option 'by X' is not selected by default, even though I marked it with ng-value 'true'.

(2) After selecting 'by All' option, I am NOT able to select 'by X' option.

Could you please help to fix these issues ?

Answer

I updated your code. Please look at the jsFiddle.

There were the following problems with your code:

  1. $scope.inputCreatedBy should've been set to byX to get it selected by default.
  2. $scope.displayFiles should've been cleared each time toggleSelection function was used.
  3. ngValue should be used to bind an angular expression to the value attribute of the input element. So the directive is not required in your case.