Home > Back-end >  angularjs ng-repeat radio buttons
angularjs ng-repeat radio buttons

Time:10-07

This code makes 2 sets of 3 radio buttons. One set of individual radio buttons and one set of radio buttons constructed with an ng-repeat. Both sets of radio buttons can be selected with the buttons A-C or they can be clicked on themselves.

However: when you have clicked on the ng-repeat radio buttons, they are no longer selected with the buttons A-C. Why?

angular.module('radioExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.color = {
      name: 'blue'
    };
    $scope.radiomodel = 'blue';
    $scope.radiovalues = ['red', 'green', 'blue'];

    $scope.clickA = function() {
      $scope.color.name = 'red';
      $scope.radiomodel = 'red';
    }

    $scope.clickB = function() {
      $scope.color.name = 'green';
      $scope.radiomodel = 'green';
    }

    $scope.clickC = function() {
      $scope.color.name = 'blue';
      $scope.radiomodel = 'blue';
    }

    $scope.radioclick = function(index) {
      $scope.clickvalue = index;
    }

    $scope.radiochange = function(index) {
      $scope.changevalue = index;
    }

  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>

<body ng-app="radioExample">
  <form name="myForm" ng-controller="ExampleController">
    <button ng-click="clickA()">A</button>
    <button ng-click="clickB()">B</button>
    <button ng-click="clickC()">C</button>
    <br/> individual <br/>
    <label>
    <input type="radio" ng-model="color.name" value="red">
    Red
  </label><br/>
    <label>
    <input type="radio" ng-model="color.name" value = "green">
    Green
  </label><br/>
    <label>
    <input type="radio" ng-model="color.name" value="blue">
    Blue

  </label><br/> ng-repeat
    <div ng-repeat="i in [0, 1, 2]">
      <input type="radio" name="myradio" value="{{radiovalues[$index]}}" ng-model="radiomodel" ng-click="radioclick($index)" ng-change="radiochange($index)"> {{$index}} ({{radiovalues[$index]}}) </input>
    </div>
    <tt>color = {{color.name | json}}</tt><br/>
  </form>
</body>

CodePudding user response:

The problem is that you use wrong ng-model inside ng-repeat. I changed

ng-model="radiomodel" 

into

ng-model="color.name"

Here is the working example: https://jsfiddle.net/avgustin/x5q8kfdv/

  • Related