maria maria - 8 months ago 36
AngularJS Question

angularjs radio acting weird

im using this approach:

<tr class="radio-row" ng-repeat="topurchase in vm.firmstopurchase">

<td >
<input type="radio" ng-model="color" value="red">
{{ }}</td>


but in my code, i can somehow select multiple of them, and they have weird names:

while looking in the source code after the ng-repeat is done i see:

<input type="radio" ng-model="color" value="red" class="ng-valid ng-not-empty ng-dirty ng-valid-parse ng-touched" name="38" style="">

all different
attribute for each of the ng-repeat loops.

Why is it acting like that? How can i call it with color? cause that wont work currently..


You are a victim of scope inheritance issues here. There is a rule in Angular - "Always use a dot in ng-model. ng-repeat creates a new child scope, and any ng-model without a dot is not accessible outside the repeat. See Nuances of scope prototype inheritance for a more in depth look.

you appear already to be using Controller As (you have a vm binding). Using vm.color will help here.

Also, once these are all hooked up correctly to the controller, they will all select simultaneously, since you are setting all their values to the same thing. you can use ng-value to hook the radio up to the object, or to a property on the object. (eg. ng-value="topurchase" would set the ng-model to the specific object, or ng-value="" would set it equal to the name property.

In summary, change ng-model to reference your controller, and use ng-value instead of value.

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

app.controller('MainCtrl', function() {
  var vm = this;
   vm.firmstopurchase = [
     {name: 'red', number: 1},
     {name: 'blue', number: 2},
     {name: 'yellow', number: 3},
<!DOCTYPE html>
<html ng-app="plunker">

  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
    document.write('<base href="' + document.location + '" />');
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.x" src="" data-semver="1.5.8"></script>
  <script src="app.js"></script>

<body ng-controller="MainCtrl as vm">
    <tr class="radio-row" ng-repeat="topurchase in vm.firmstopurchase">

        <input type="radio" ng-model="vm.color" ng-value="topurchase"> {{ }}</td>