【问题标题】:Getting radio button value when button is clicked is not working angularjs单击按钮时获取单选按钮值不起作用
【发布时间】:2014-11-26 07:33:34
【问题描述】:

我是 angularjs 的新手。我想在用户单击按钮时获取单选按钮的值,但我的运气不好,它不起作用。这是代码

<label class="item item-radio">
    <input type="radio" name="group" ng-model="user.answer" value="{{questions.quiz_ans_opt1}}">
    <div class="item-content item-body">a) {{questions.quiz_ans_opt1}}</div><i class="radio-icon ion-checkmark"></i>
</label>
<label class="item item-radio item-body">
    <input type="radio" name="group" ng-model="user.answer" value="{{questions.quiz_ans_opt2}}">
    <div class="item-content item-body">b) {{questions.quiz_ans_opt2}}</div><i class="radio-icon ion-checkmark"></i>
</label>
<button class="button button-balanced button-block" ng-click="submitAnswer(user)">Submit</button>

这里是控制器

$scope.submitAnswer = function(user) {
    //it output undefined error
    alert(user);
}

我还想在选中单选按钮之前禁用该按钮,我怎样才能做到这一点?

【问题讨论】:

  • 你能针对你的问题创建一个 plunkr 吗?

标签: javascript android angularjs ionic-framework


【解决方案1】:

请看这个,

试试这个,

在html中,

<body ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>
  <input type="radio" ng-model="user.answer" ng-value="'option a'">
  <label>option a</label>
  <br>
  <input type="radio" ng-model="user.answer" ng-value="'option b'">
  <label>option b</label>
  <br>
  <input type="radio" ng-model="user.answer" ng-value="'option c'">
  <label>option c</label>
  <br>
  <input type="radio" ng-model="user.answer" ng-value="'option d'">
  <label>option d</label>
  <br>
  <button ng-disabled="!user.answer" ng-click="submitAnswer(user)">Submit</button>
</body>

在 app.js 中,

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.submitAnswer=function(user){

    alert(user.answer);

  }
});

这是相同的plunker 演示

【讨论】:

  • 为了防止多选按钮,请确保每个单选按钮的名称相同,例如:
【解决方案2】:

虽然有点晚了,但我想发布第二种方法,因为您使用的是 Ionic-Framework。

如果您有动态数量的单选按钮选项,这些选项是由后端数据驱动的 [即使您有一个静态 单选按钮集,你可以将其转换为正式的],那么你应该使用 Ionic 的单选按钮:

IE,在你的 HTML 中:

<ion-radio ng-repeat="user in userAnswers"
           ng-value="user.answer"
           ng-model="finalAnswer">
  {{ item.text }}
</ion-radio>

在你的控制器中:

$scope.userAnswers = [
    { text: "Backbone", answer: "bb" },
    { text: "Angular", answer: "ng" },
    { text: "Ember", answer: "em" },
    { text: "Knockout", answer: "ko" }
  ];

  $scope.finalAnswer = 'ng';

更多详情请见official documentationCodePen Demo

【讨论】:

    【解决方案3】:

    这篇文章真的帮助了我。我最终将所有单选按钮 ng-click 事件更改为 ng-change。希望这会有所帮助。

    AngularJS - Trigger when radio button is selected

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 2013-12-27
      • 2014-03-24
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      相关资源
      最近更新 更多