AngularJS单选按钮奇怪的行为

时间:2013-09-19 15:13:40

标签: javascript angularjs radio-button

我正在尝试做一件简单的事情:使用AngularJS将我的JSON对象列表放在表单上。 我想将其中一个参数映射到HTML radiobutton控件。这是HTML模板:

<div ng-app="myApp" ng-controller='MainController'>
    <div ng-repeat="channel in channels">
        <p>Case {{ channel.schedule.timeOfDay }}</p>
        <input type="radio" ng-model="channel.schedule.timeOfDay" ng-value="0" name="channel">Case 0</input>
        <input type="radio" ng-model="channel.schedule.timeOfDay" ng-value="1" name="channel">Case 1</input>
        <input type="radio" ng-model="channel.schedule.timeOfDay" ng-value="2" name="channel">Case 2</input>
        <input type="radio" ng-model="channel.schedule.timeOfDay" ng-value="3" name="channel">Case 3</input>
        <hr>
    </div>
</div>

一个简单的控制器:

var app = angular.module('myApp', []);
app.controller('MainController', function ($scope) {
    $scope.channels = [{
        "id": 4,
        "subject": null,
        "body": "Votre utilisation de données a atteint (SMS) [Percentage]%",
        "schedule": {
            "dayOfWeek": 24,
            "timeOfDay": 3,
            "from": 1,
            "to": 4
        },
        "channelType": 0
    }, {
        "id": 5,
        "subject": null,
        "body": "Votre utilisation de données a atteint (USSD) [Percentage]%",
        "schedule": {
            "dayOfWeek": 18,
            "timeOfDay": 1,
            "from": 0,
            "to": 0
        },
        "channelType": 1
    }, {
        "id": 6,
        "subject": "Avertissement",
        "body": "Votre utilisation de données a atteint (E-Mail) [Percentage]%",
        "schedule": {
            "dayOfWeek": 33,
            "timeOfDay": 3,
            "from": 15,
            "to": 22
        },
        "channelType": 2
    }]
});

I created jsfiddle for this example/

所以,正如你所看到的那样,我将channel.schedule.timeOfDay映射到radiobutton控件,而且这里出现了奇怪的行为。 radiobutton不反映第一和第二阵列元素的值,但是对第三个阵列元素执行。有人请解释一下发生了什么?

1 个答案:

答案 0 :(得分:0)

我也有点想把你的html更改为:(注意每个选项组的名称必须是唯一的)

<div ng-app="myApp" ng-controller='MainController'>
<div ng-repeat="channel in channels | orderBy:'body': false">
    <p>Case {{ channel.schedule.timeOfDay }} {{ channel.id }}</p>
    <input type="radio" ng-model="channel.schedule.timeOfDay" ng-value="0" name="t{{channel.id}}">Case 0</input>
    <input type="radio" ng-model="channel.schedule.timeOfDay" ng-value="1" name="t{{channel.id}}">Case 1</input>
    <input type="radio" ng-model="channel.schedule.timeOfDay" ng-value="2" name="t{{channel.id}}">Case 2</input>
    <input type="radio" ng-model="channel.schedule.timeOfDay" ng-value="3" name="t{{channel.id}}">Case 3</input>
    <hr>
</div>