简体   繁体   English

将对象的键绑定到AngularJS中的无线电输入值

[英]Bind object's key to radio input's value in AngularJS

I'm having an object in my controller like the following: 我在控制器中有一个对象,如下所示:

$scope.colors = {
    green: "Green",
    yellow: "Yellow",
    red: "Red"
};

I'm trying to create the radio inputs dynamically and then bind the value of the input to the object's key. 我正在尝试动态创建无线电输入,然后将输入值绑定到对象的密钥。

I'm trying something like this: 我正在尝试这样的事情:

<label ng-repeat="color in colors">{{color}}
<input type="radio" ng-model="model.color" name="name" ng-value="{{color}}" ng-change="test()" />
</label>

but I can't make it work. 但我不能让它发挥作用。

Here is my fiddle 这是我的小提琴

You never define your model on the controller. 您永远不会在控制器上定义您的模型。 I have updated your fiddle to do so: https://jsfiddle.net/Xsk5X/1380/ 我已经更新了你的小提琴: https//jsfiddle.net/Xsk5X/1380/

  $scope.model = {"color":"test"};

I also added a <span> which displays the selected color to show it is working 我还添加了一个<span> ,它显示所选的颜色以显示它正在工作

I've added a new function and variable - $scope.createColors and $scope.colorsToBind . 我添加了一个新函数和变量 - $scope.createColors$scope.colorsToBind

The function will convert $scope.colors into an array of just the object keys, and then create a new array of Objects containing the key and value for that color, but as accessible fields; 该函数将$scope.colors转换为仅包含对象键的数组,然后创建一个新的Objects数组,其中包含该颜色的键和值,但作为可访问的字段; each will look like {key:"green", value: "Green"} . 每个看起来都像{key:"green", value: "Green"} Once we have the array of these objects, the function will then set the value of $scope.colorsToBind to that array. 一旦我们拥有了这些对象的数组,该函数就会将$scope.colorsToBind的值设置为该数组。

Your html is now using that new variable colorsToBind , and is displaying the value of each object but binding to the key of each one. 您的html现在使用新的变量colorsToBind ,并显示每个对象的value ,但绑定到每个对象的key

I managed to come with a cleaner solution. 我设法提供了一个更清洁的解决方案。

<label ng-repeat="(key, value) in colors">
    <input type="radio" ng-model="model.color" name="name" ng-value="key" /> {{value}}
</label>

here is the fiddle 这是小提琴

you can do like this also : 你也可以这样做:

<label ng-repeat="color in colors">{{color}}
<input type="radio" ng-model="colors" name="name" value="{{color}}" ng-change="test()" />
</label>

$scope.test = function() {
   alert($scope.colors);
};

Jsfiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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