Getting switch value on button click does not work angularjs

I am new to angularjs.I want to get the value of the switch when the user clicks the button, but my failure is not working. Here is the code

<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> 

Here is the controller

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

I also want to disable the button until the switch is checked, how can I do this?

+5
source share
3 answers

Please take a look at this,

Try it,

In 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> 

In app.js,

 var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $scope.submitAnswer=function(user){ alert(user.answer); } }); 

Here is the plunker daemon for the same

+1
source

Although a bit late, I would like to post a second approach, since you are using the Ionic-Framework.

If you even have a dynamic number of switch parameters that are controlled by the backend data [Even if you have a static switch, you can convert it to a formal one], Then you should use ionic radio buttons instead:

IE, In your HTML:

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

And in your controller:

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

More information can be found in the official documentation and CodePen Demo

0
source

This post really helped me. I ended up changing all of my ng-click-event switches to ng-change. Hope this helps.

AngularJS - trigger when selecting radio button

0
source

Source: https://habr.com/ru/post/1206519/


All Articles