connectwithpalaniappan
connectwithpalaniappan

Reputation: 973

Angularjs multiple radio button, auto-select if only one is present

Am successful in building angularjs app of multiple dependent radio button.

But have a requirement to default select a radio button if only one is present.

Tried out the stuff in Angularjs: radio button checked, but it doesn't work for multiple radio buttons.

Code Explanation:

HTML Code: I have two radio buttons. Second set of radio buttons are generated based on the first.

<div>
            <ul >
              <li> Part One : </li>
                        <li ng-repeat="f in Input"><input type="radio" name="oneInput" ng-value="f" ng-model="$parent.One">&nbsp;{{f.Name}}&nbsp;</input></li>
    </ul>
    </div><br/>
    <div>
              <ul>
                  <li> Part Two : </li>
                  <li ng-repeat="u in filteredUser = (One.User | filter: { Valid: 'Y' })"><input type="radio" name="userInput" ng-value="u" ng-model="$parent.Two">&nbsp;{{u.Name}}&nbsp;</input></li>
            </ul>
    </div><br/>

If I select a radio button in first set, and second set has only one radio button, it must be selected by default.

For example, if I select D, I get the D2 radio button which must be selected.

Complete Code @ http://plnkr.co/edit/dY2syxNWobxHpiVKIuux?p=preview

Appreciate your response.

Upvotes: 2

Views: 2885

Answers (1)

sylwester
sylwester

Reputation: 16498

please see here: http://plnkr.co/edit/QVvN6rP3wlyxbOJaAGHQ?p=preview

 $scope.$watch('One', function(value) {

    if (value.Name) {

      var users = $filter('filter')($scope.Input, value);

      var vaildUsers = $filter('filter')(users[0].User, {
        Valid: "Y"
      });


      if (vaildUsers.length == 1) {

        $scope.Two = vaildUsers[0];

      } else

      {

        $scope.Two = {};

      }
    }

  });

Upvotes: 3

Related Questions