我的控制器名称为三色。
<script>
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.color = [{
name: "Red"
},
{
name: "green"
},
{
name: "Blue"
}
];
}]);
</script>
我想创建3个单选按钮,显示相应的颜色并在屏幕上显示
<label>
<input type="radio" ng-model="color.name" value="red"> Red
<tt>color = {{color.name }}</tt>
</label>
我希望直接从数组中获取值,而不是从值中获取值。我怎么做?
我试过了值=&#34; color.name&#34;但是不要跑。
谢谢。答案 0 :(得分:1)
你需要的只是一个ng-repeat。这是一个工作样本。
var app = angular.module("sampleApp", []);
app.controller("sampleController", ["$scope",
function($scope) {
$scope.colorName = "Blue";
$scope.colors = [{
name: "Red"
}, {
name: "green"
}, {
name: "Blue"
}];
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
<div ng-controller="sampleController">
<label ng-repeat="color in colors">
<input type="radio" ng-model="$parent.colorName" ng-value="color.name" name="color-picker" />{{color.name}}
</label>
<tt>color = {{colorName}}</tt>
</div>
</div>
或者使用controllerAs语法,你可以这样做。
var app = angular.module("sampleApp", []);
app.controller("sampleController", ["$scope",
function($scope) {
$scope.colorName = "Blue";
$scope.colors = [{
name: "Red"
}, {
name: "green"
}, {
name: "Blue"
}];
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
<div ng-controller="sampleController as sc">
<label ng-repeat="color in colors">
<input type="radio" ng-model="sc.colorName" ng-value="color.name" name="color-picker" />{{color.name}}
</label>
<tt>color = {{sc.colorName}}</tt>
</div>
</div>