How to get the ng-value value of checkbox in Angularjs/Ionic

Asked

Viewed 1,833 times

1

Imagine a traditional application in Angularjs

<!DOCTYPE html>
<html ng-app>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <title></title>
</head>
<body>

    <input type="input" ng-model="resultado">
    Resultado: {{resultado}}<br>


Resultado {{escolha}}

</body>
</html>

Now, imagine that I want to make dataBind contained in the ng-value of a checkbox

<!DOCTYPE html>
<html ng-app>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <title></title>
</head>
<body>

<input type="checkbox" ng-model="escolha" ng-value="google">google<BR>
<input type="checkbox" ng-model="escolha" ng-value="yahoo">yahoo<BR>
<input type="checkbox" ng-model="escolha" ng-value="microsoft">microsoft<BR>

Resultado {{escolha}}

</body>
</html>

I would also like to know if it is possible to do with radio in the IONIC standard

<ion-radio ng-model="escolha" ng-value="'A'">google.com</ion-radio>
<ion-radio ng-model="escolha" ng-value="'B'">yahoo.com</ion-radio>
<ion-radio ng-model="escolha" ng-value="'C'">microsoft.com</ion-radio>

1 answer

2


I put down an example of radio using AngularJS for you to take as an example. You just need to link the ng-model with the variable you want to assign value. I noticed that you describe the behavior of a radio and not of a check, after all it only needs a value.

angular
  .module('app', [])
  .controller('CheckController', CheckController);

function CheckController() {
  var vm = this;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="CheckController as vm">
  <input type="radio" ng-model="vm.opcao" value="A"/>
  <input type="radio" ng-model="vm.opcao" value="B"/>
  <input type="radio" ng-model="vm.opcao" value="C"/>
  <input type="radio" ng-model="vm.opcao" value="D"/>
  <input type="radio" ng-model="vm.opcao" value="E"/>

  <br>
  <br>

  Opção escolhida: {{vm.opcao}}
</div>

In case you only use ng-value if you need a dynamic value for the option:

angular
  .module('app', [])
  .controller('CheckController', CheckController);

function CheckController() {
  var vm = this;

  vm.a = 'yahoo';
  vm.b = 'google';
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="CheckController as vm">
  <input type="radio" ng-model="vm.opcao" ng-value="vm.a"/>
  <input type="radio" ng-model="vm.opcao" ng-value="vm.b"/>

  <br>
  <br>

  Opção escolhida: {{vm.opcao}}
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.