1

I have two radio buttons, and they should be checked depending on some condition.

<input data-ng-checked="user.contract1 || user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="true"> Yes
<input data-ng-checked="!user.contract1 && !user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="false"> No

So here, we have a model user.agreed which holds true/false depending on whether that user has agreed:

  • If the user has agreed to either contract, then user.agreed = true

  • If the user has not agreed to either contract, then user.agreed = false

I have noticed that when I load the page, the radio button is sometimes selected on 'No' instead of 'Yes'. I think this has to do with the digest cycle completing before my data has loaded from the server.

But I thought doing this would be two-way binding, so if the user model changes, the view will change. When data gets loaded from the server, the model gets updated with the new info, and so the view should reflect this change.

But that's not happening. How can I force ng-checked to reflect my model changes?

EDIT controller code:

app.controller('TestCtrl', ["QueryService", function(QueryService) {

    $scope.user = {
        contract1 = false;
        contactt2 = false;
    };


    QueryService.getUser().success(function(user) {
        $scope.user = user;
    });

});
rublex
  • 1,893
  • 5
  • 27
  • 45

1 Answers1

2

Your issue could be because of ng-checked along with ng-model. You cannot use both of them together. Using ng-checked will not set the value of ng-model, it will just set the checked property on the element. Instead of using ng-checked set the value of ng-model instead and use same name for radio button so that they act as a group.

You could just do:

<input name="agree" data-ng-model="user.agreed" type="radio" data-ng-value="true"> Yes
<input name="agree" data-ng-model="user.agreed" type="radio" data-ng-value="false"> No

and set initial value

 user.agreed = user.contract1 || user.contract2; //Or whatever initial value
PSL
  • 123,204
  • 21
  • 253
  • 243