Angular JS: input[radio] doesn't work

ⅰ亾dé卋堺 提交于 2019-11-28 12:43:40

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/36244427/angular-js-inputradio-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!