简体   繁体   中英

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/

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

I also added a <span> which displays the selected color to show it is working

I've added a new function and variable - $scope.createColors and $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; each will look like {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.

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.

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

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