角度单选按钮 - 检查时未定义的值

时间:2017-04-28 10:42:54

标签: angularjs radio-button

我在Angular 1中有像http://jsfiddle.net/md3coyzn/1/这样的单选按钮,我需要在单击单选按钮时将值更改为true / false,但我仍然得到未定义的值,并且不知道为什么

$scope.radioContent = [
    {txt: 'One', checked: true},
    {txt: 'Two', checked: false}
];


<div ng-repeat="radio in radioContent">
    <input type="radio" name="group" ng-model="radio.checked">{{radio.txt}} ---> {{radio.checked}}
</div>

2 个答案:

答案 0 :(得分:1)

as ng-repeat 创建自己的范围。所以你必须使用$ parent

进行访问

HTML

<div ng-repeat="radio in radioContent track by $index">
        <input type="radio" name="group[$index]" ng-model="$parent.selectedRadio" ng-change="$parent.radioChecked()" ng-value="radio" >{{radio.txt}}      
    </div>

JS

.controller('ExampleCtrl', ['$scope', function ($scope) {
    $scope.selectedRadio;
    $scope.radioContent = [
        {txt: 'One', checked: true},
        {txt: 'Two', checked: false}
    ];

    $scope.radioChecked = function () {
        console.log('selectedRadio', $scope.selectedRadio);
        $scope.selectedRadio.checked = !$scope.selectedRadio.checked
    }
}]);

请查看working Fiddle

希望它可以帮到你。

答案 1 :(得分:0)

用于切换单选按钮值的ng-click方法。

请注意,该按钮的value属性与ng-model属性冲突,因此必须删除后一个属性。

angular.module('ExampleApp', [])

.controller('ExampleCtrl', ['$scope', function ($scope) {
console.clear();
    $scope.radioContent = [
        {txt: 'One', checked: true},
        {txt: 'Two', checked: false}
    ];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="ExampleApp" ng-controller="ExampleCtrl">
    <div ng-repeat="radio in radioContent">
        <input type="radio" name="group" value="{{radio.checked}}" ng-click="radio.checked = !radio.checked">{{radio.txt}} ---> {{radio.checked}}
    </div>
</div>