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

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><inputtype="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><inputtype="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 radio with 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>
    
asked by anonymous 29.08.2017 / 05:48

1 answer

2

I've put an example of radio using AngularJS so that you take as an example. You only need to bind ng-model to the variable you want to assign value to. I noticed that you describe the behavior of a radio and not 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><divng-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><divng-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>
    
29.08.2017 / 09:23