0

I'm building a dynamic list of radio inputs based on JSON data coming from an API.

I'm using ngRepeat + track by, input[radio] and ngValue.

Any new XHR request will refresh the data in the scope but the currently checked radio (if any) will be unchecked.


See this plnkr demo: http://embed.plnkr.co/2q1A7krBzxIjkfwhXYcK/preview


This can be solved by using the interpolation directive in ngValue, but it feels like I'm doing it wrong:

<input type="radio" name="c" ng-value="{{ choice }}" ng-model="selected.choice" required>

This can also be solved by using ng-init but it still feels like I'm doing it wrong:

<input type="radio" name="c" ng-init="c = choice" ng-value="c" ng-model="selected.choice" required>

Can somebody please explain me what's going on?


Related questions:

1 Answer 1

1

Angular is using equality by reference here to figure out which radiobutton gets ticked, so when you replace the entire xhrData object, the reference is lost.

You can see how this works if you add

$scope.selected.choice = $scope.xhrData.all.choices[2]

to the bottom of your fetcher-function.

I'm afraid you'll have to save the choice before replacing the xhrData object and then reset it after fetching new data. I'm not aware of any other way to do it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your answer :) I wish AngularJS used some kind of isEqual underscorejs.org/#isEqual for comparison.
Yes, that would have been useful in a lot of cases. I suppose they have a good reason for using object references, though I don't know what it is. I think you can get around this by using a primitive type for your ng-model but that opens up a door to new problems because you then have to write code to find the correct object that matches the model. Which you have to do anyway if you want to save the selection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.