jetcom
jetcom

Reputation: 955

Enable/disable button based on radio button selection in AngularJS

I have items in a radio button list (using ng-repeat) with a button (initially disabled with ng-disabled) to continue. When a radio button is selected, I want to enable the "Continue" button.

What's the right way to do this in Angular?

Relevant JS:

$scope.companies = [{
        "id": 3,
        "name": "Twitter"
    }, {
        "id": 2,
        "name": "Google"
    }, {
        "id": 1,
        "name": "Apple"
    }]

Relevant HTML:

<table>
  <tr ng-repeat="company in companies">
     <td>
       <input type="radio" ng-model="companyId" name="companyId" value="{{company.id}}" />{{company.name}}
      </td>
  </tr>
</table>

<button ng-disabled="!companyId">Continue</button>

Jsfiddle

Thanks!

Upvotes: 6

Views: 36976

Answers (1)

JB Nizet
JB Nizet

Reputation: 692231

ngRepeat creates a new scope, which is a child scope of the scope used by the button. You can fix it by using

<input type="radio" ng-model="$parent.companyId" .../>

See http://jsfiddle.net/UZkM8/1/

But a better solution would be to update an object that is already in the scope:

$scope.userChoice = {};

<input type="radio" ng-model="userChoice.companyId" .../>

<button ng-disabled="!userChoice.companyId">Continue</button>

See http://jsfiddle.net/UZkM8/3/

Upvotes: 18

Related Questions