Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable/disable button based on radio button selection in AngularJS

Tags:

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!

like image 801
jetcom Avatar asked Aug 10 '13 22:08

jetcom


1 Answers

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/

like image 102
JB Nizet Avatar answered Oct 21 '22 01:10

JB Nizet