【问题标题】:angularjs ng-repeat radio buttonsangularjs ng-repeat 单选按钮
【发布时间】:2022-11-11 16:32:05
【问题描述】:

此代码制作 2 组 3 个单选按钮。一组单独的单选按钮和一组使用 ng-repeat 构造的单选按钮。可以使用按钮 A-C 选择两组单选按钮,也可以单击它们本身。

但是:当您单击 ng-repeat 单选按钮时,它们不再被按钮 A-C 选中。为什么?

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>

【问题讨论】:

    标签: javascript angularjs radio-button angularjs-ng-repeat


    【解决方案1】:

    问题是您在 ng-repeat 中使用了错误的 ng-model。我变了

    ng-model="radiomodel" 
    

    进入

    ng-model="color.name"
    

    这是工作示例:https://jsfiddle.net/avgustin/x5q8kfdv/

    【讨论】:

    • 非常感谢您的解决方案。似乎问题与模型“对象”的性质有关。 $scope.radiomodel 不起作用,但“并行”color.name2 与仅对两组单选按钮使用 color.name 一样有效
    • @notangularjsexpert 如果解决方案适合您,请接受我的回答。
    猜你喜欢
    • 2015-06-27
    • 1970-01-01
    • 2015-05-07
    • 2016-04-22
    • 2016-02-10
    • 1970-01-01
    • 2015-09-22
    • 2014-06-14
    • 1970-01-01
    相关资源
    最近更新 更多