简体   繁体   中英

Bind JSON object as radio data in AngularJS

I'm trying to solve bind problem in my application. Similar questions are exists on Stackoverflow, but they do not fully describes my scenario.

I have an radio group created using repeater. Each style value is the Object so I'm using ng-value directive to bind them correct

        <label ng-repeat="style in styles">
            <input type="radio" ng-model="formData.style" ng-value="style">
            {{style.name}}
        </label>

And my controller logic is very simple:

var first = {
   name: "First Name",
   value: "First Value"
};

var second = {
   name: "Second Name",
   value: "Second Value"
};

var third = {
   name: "Third Name",
   value: "Third Value"
};

$scope.styles = [first, second, third];

$scope.formData = {};

//this code works and my screen shows 'second' as selected option
$scope.formData.style = second; 

//this code do not works and my screen do not show 'Second name' as selected
//$scope.formData.style = { 
//       name: "Second Name",
//       value: "Second Value"
//    };

This code works as expected. I'm setting my selection and form shows selected option.

But in my particular example I don't have reference to my second value and I need to take this data from third control, so my updated code will looks like:

$scope.formData.style = {
   name: "Second Name",
   value: "Second Value"
};

And this behavior do not works - I do not see radio selection on my screen.

Here is my fiddle https://jsfiddle.net/vadimb/L7uw3oos/3/

The reason here is because you are binding the radio button to the exact property on your model $scope.formData.style which in the first example is set to second which is an item within your $scope.styles array.

When you bind your radio button to a new object:

$scope.formData.style = {
    name: "Second Name",
    value: "Second Value"
};

You are not binding it to the object that is in the $scope.styles array, $scope.formData.style is now it's own completely separate object.

If you want to set it dynamically, you must lookup the item you want from within $scope.styles .

Using Underscore:

$scope.formData.style = _.findWhere($scope.styles, { name: "Second Name"})

Using Pure JS:

function getFromArray(array, value) {
    for(var i = 0; i < array.length; i++) {
        if (array[i].name.toLowerCase() == value.toLowerCase()) {
            return array[i];
        }
    }
}

$scope.formData.style = getFromArray($scope.styles, "Second Name");

Although I'd recommend using some sort of Id instead of a magic string.

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