如何将单选按钮绑定到下拉菜单中

How to bind radio a drop down menu with radio buttons?

本文关键字:下拉菜单 绑定 单选按钮      更新时间:2023-09-26

如何将下拉菜单与单选按钮同步,以便当我选中一个按钮时,下拉菜单会使用相同的选项动态更改?

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.colors = [
        {model : "Red"},
        {model : "Green"},
        {model : "Blue"},
        {model : "Purple"}
    ];
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>What is your favorite color?</p>
<select ng-model="selectedColor" ng-options="x.model for x in colors">
</select>
<input type="radio" ng-model="colors.model" value = "{{selectedColor.model}}"> Red
<input type="radio" ng-model="colors.model" value = "{{selectedColor.model}}"> Green
<input type="radio" ng-model="colors.model" value = "{{selectedColor.model}}"> Blue
<input type="radio" ng-model="colors.model" value = "{{selectedColor.model}}"> Purple
</div>
</body>
</html>
感谢

一种方法是使用相同的ng-model,这意味着您需要仔细考虑无线电的对应值,以及数组中的对象

 var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.colors = [
        {model : "Red"},
        {model : "Green"},
        {model : "Blue"},
        {model : "Purple"}
    ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>What is your favorite color?</p>
<select ng-model="selectedColor" ng-options="x.model for x in colors">
</select>
<input name='rad' type="radio" ng-model="selectedColor" ng-value="colors[0]"> Red
<input name='rad' type="radio" ng-model="selectedColor"  ng-value="colors[1]" > Green
<input name='rad' type="radio" ng-model="selectedColor"  ng-value="colors[2]"> Blue
<input name='rad' type="radio" ng-model="selectedColor"  ng-value="colors[3]"> Purple
</div>

其他几种方法是在每个函数上使用ng-change并更新其他内部函数,或者在不同的ng-model上使用一个手表并更新这些手表中的其他