1

I'm using ng-value to set a radio inputs value to an object so when the value matches the ng-model object it should result in the radio being checked. Here's an example and plunker.

<script>
angular.module('test', [])
.controller('testController', ['$scope', function($scope) {

  $scope.Obj = {
    "id": "1",
    "value": "green"
  };
  $scope.ObjTwo = {
    "id": "2",
    "value": "red"
  };
  $scope.ObjThree = {
    "id": "3",
    "value": "blue"
  };

  $scope.modelObj = {
    "id": "3",
    "value": "blue"
  };

}]);
</script> 

<form name="myForm" ng-controller="testController">
  <label>
   <input type="radio" ng-model="modelObj" ng-value="Obj">
   {{Obj}}
  </label><br/>
  <label>
    <input type="radio" ng-model="modelObj" ng-value="ObjTwo">
    {{ObjTwo}}
  </label><br/>
  <label>
    <input type="radio" ng-model="modelObj" ng-value="ObjThree">
    {{ObjThree}}
  </label><br/>

  color = {{modelObj}}<br/>

https://plnkr.co/edit/aAISUTEqdGkpVrEJt0uq?p=preview

It seems to work fine when clicking the radio buttons as the modelObj is updated to the relevant object. But why isn't the third radio input(objThree) checked on load? I thought because $scope.Objthree is equal to $scope.modeObj as set in the controller that it would check the radio input?

2 Answers 2

1

Working example: https://plnkr.co/edit/J3QQM0z0nSC9KulHzQGI?p=preview

Try $scope.modelObj = $scope.ObjThree;. This will set the reference of $scope.modelObj equal to the ObjThree object, rather than just creating a new object with a new reference that happens to have the same properties. In general, JavaScript uses referential equality to compare objects and only uses value equality to compare elementary data types, such as numbers and strings.

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

Comments

0

You can to set in ngInit:

ng-init="modelObj = ObjThree"

Could be:

<form name="myForm" ng-controller="testController" ng-init="modelObj = ObjThree">

Comments

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.