如何获取所选单选按钮的值

时间:2019-01-01 12:04:40

标签: angularjs

我正在尝试使用以下代码获取选定的单选按钮值,但我正在获取未定义的值。我的错是什么?

html

<form name="form" class="form-horizontal" role="form">

    <!-- RADIO BUTTONS -->
    <div class="form-group">
        <label class="col-sm-2 control-label">Clouds</label>
        <div class="col-sm-6">
            <label class="radio-inline" ng-repeat="option in entity.fields">
                <input type="radio" ng-model="data" name="option.name" value="{{option.id}}">
                {{option.name}}
            </label>
        </div>
    </div>

    <br />
    <button type="submit" id="submit" ng-click="save(data)">Submit</button>
    <br />

</form>

控制器

routerApp.controller('DynamicController2', ['$scope', function ($scope) {
    // we would get this from the api
    $scope.entity = {
        name: "my favorite fruits",
        fields:
            [{ id: 1, name: "orange" }, { id: 2, name: "pink" }, { id: 3, name: "gray" }, { id: 4, name: "cyan" }]
    };
    $scope.save = function (data) {
        alert(data);
    }
}]);

1 个答案:

答案 0 :(得分:1)

在控制器中未定义ng-modal中使用的变量'data'。您需要将“数据”变量定义为$ scope。然后,无需将变量传递给函数save。 这是您的控制器应该如何

routerApp.controller('DynamicController2', ['$scope', function ($scope) {
// we would get this from the api
 $scope.data;
$scope.entity = {
    name: "my favorite fruits",
    fields:
        [{ id: 1, name: "orange" }, { id: 2, name: "pink" }, { id: 3, name: "gray" }, { id: 4, name: "cyan" }]
};
$scope.save = function () {
    alert($scope.data);
}

}]);

您在html中的按钮应类似于:

<button type="submit" id="submit" ng-click="save()">Submit</button>

希望这能解决您的问题。