Search code examples
javascriptangularjscheckboxradio-button

Angular JS: input[radio] doesn't work


Here is my code:

<div ng-controller="TestController">
    <input ng-repeat="item in array" ng-model="selected.name" value="{{item.name}}" type="radio"></input>
</div>
<script type="text/javascript">
    var app = angular.module('app', []);
    app.controller('TestController', function ($scope) {
        $scope.array = [{
            name: 'lee',
            seq: 1,
        }, {
            name: 'tom',
            seq: 2,
        }, {
            name: 'jack',
            seq: 3,
        }];

        $scope.selected = $scope.array[0];
    });
</script>

When the page is show, the default checked radio box is correct. But it can not be un-check,and I can only switch between the other two checkbox? How can I fix this problem?


Solution

  • ng-repeat create new scope so you should determine parent scope.

    for more info see https://docs.angularjs.org/api/ng/directive/ngRepeat

    var app = angular.module('app', []);
        app.controller('TestController', function ($scope) {
            $scope.array = [{
                name: 'lee',
                seq: 1,
            }, {
                name: 'tom',
                seq: 2,
            }, {
                name: 'jack',
                seq: 3,
            }];
    
            $scope.selected = $scope.array[0].name;
        });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="TestController">
      <div ng-repeat="item in array">
         <input type="radio" ng-model="$parent.selected"  
        ng-value="item.name" > 
      </div>
    </div>