marek marek - 5 months ago 8
AngularJS Question

AngularJS value from radio to $http.post

I wold like to ask you how to get value from radio and send it with $http.post using AngularJS. Here is some example

HTML

<input name="group1" type="radio" id="test1" value="4"/>
<label for="test1">Four paintings</label>

<input name="group1" type="radio" id="test2" value="6" />
<label for="test2">Six paintings</label>

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


One radio button has value of 4 and another 6. These numbers I would like to send to Angular and then to DB

Angular

$scope.submit = function(){
if ( radioValue == 4 ) {
$http.post(apiURL, {
numberOfpaintings: ??, // radioValue
...
});
} else if( radioValue == 6 ) {
$http.post(apiURL, {
numberOfpaintings: ??, // radioValue
...
});
}
}


That 'radioValue' is just some made up value that should somehow store that value from radioButtons.
Thanks!

Answer

try like this

Plunker : http://plnkr.co/edit/b3AAr9XlVcS0IW962tUT

In script:

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

app.controller('MainCtrl', function($scope,$http) {
  $scope.paintings = 4;

  $scope.submit = function(){

  alert($scope.paintings);

 $http.post(apiURL, {
    numberOfpaintings: $scope.paintings
   });
 }
});

in html

<body ng-controller="MainCtrl">

<input name="group1" ng-model="paintings" type="radio" id="test1" value="4"/>
<label for="test1">Four paintings</label>

<input name="group1"  ng-model="paintings" type="radio" id="test2" value="6" />
 <label for="test2">Six paintings</label>

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


</body>