Pergunta

All of the examples I have found show the radio button group being built by some for item in items loop but none of them show a simple accessing of the radio button group array in the angularjs controller. What I need to do is traverse through the button group array to see if any of them are in "selected" state.

var radioSelected = false;

for(var i =0; i < items.length; i++) {
  if(items[i].selected) {
     radioSelected = true;
  }
}

I have tried binding to the ng-model and accessing it .. I have tried using $scope.ButtonGroupName Nothing yeilds an array that I can traverse with a loop. Any suggestions on how to do this once VERY simple activity would be greatly appreciated.

Gotta love being forced to relearn web development because somebody broke out a new shiney hammer.

Foi útil?

Solução

You would not traverse the DOM elements. You would use the same ng-model for all the radio elements, and that would be updated whenever you change the selected state of the radio button.

<input type="radio" ng-model="assignedValue" name="myRadio" value="one">
<input type="radio" ng-model="assignedValue" name="myRadio" value="two">
<input type="radio" ng-model="assignedValue" name="myRadio" value="three">

You would $watch the $scope.assignedValue for changes instead of traversing the DOM elements.

$scope.$watch('assignedValue', function (newValue, oldValue) {
  ..do stuff here
});

See here for documentation: https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

The reason you don't traverse the DOM is because it's constantly changing. The whole point of Angular is to work off of data and not the elements themselves.

Update: Based on your comments, it sounds like only want to execute an action if a radio button has been selected.

First, a radio button should always have a selected state. Let's pretend it doesn't though. You can enable / disable / show / hide elements in angular in a couple of ways without writing additional DOM manipulation code.

Taking the example above, this button will only be enabled if the assignedValue is two.

<button ng-disabled="assignedValue != 'two'">My button</button>

You can also conditionally include content using ng-if:

<div ng-if="assignedValue == 'two'>
  My conditional content
</div>

This will also work with ng-switch

<div ng-switch on="assignedValue">
    <div ng-switch-when="two">My additional content</div>

    <div ng-switch-default>Here's switch fallback content</div>
</div>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top