一尘不染

Angular JS:input [radio]不起作用

angularjs

这是我的代码:

<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>

显示页面时,默认选中的单选框正确。但这不能取消选中,而我只能在其他两个复选框之间切换吗?我该如何解决这个问题?


阅读 283

收藏
2020-07-04

共1个答案

一尘不染

ng-repeat创建新作用域,因此您应该确定父作用域。

有关更多信息,请参见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>
2020-07-04