单击按钮时获取单选按钮值不起作用angularjs

时间:2014-11-09 13:48:04

标签: javascript android angularjs ionic-framework

我是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);
}

另外我想要禁用按钮,直到选中一个单选按钮,我该如何实现?

3 个答案:

答案 0 :(得分: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演示

答案 1 :(得分:0)

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

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

I.E,在您的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

中找到

答案 2 :(得分:0)

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

AngularJS - Trigger when radio button is selected