简体   繁体   中英

angularjs ng-repeat radio buttons

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 AC 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 AC. 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>

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM