Search code examples
angularjsangularjs-ng-repeatangularjs-ng-modelangularjs-ng-checked

How to use ng-model and ng-checked together for radio buttons, inside ng-repeat


I am trying to fetch Roles data(JSON) from a url and using ng-repeat to assign it to radio buttons(shows list of roles) and display it in MODAL. Any one option must be selected for the role currently assigned to the user.

When a user changes the selection and clicks ok, selected value should be assigned to an object, which is further passed to a URL to update the role of user.

If i use,

<div ng-repeat="item in roleDataList">
        <input type="radio"  ng-model="item"  ng-checked="item.RoleId==assignedRoleId?true:null" name="RoleRadioButton" ng-value="item"  />                   
        <span>{{item.RoleName}}</span>
</div>

then it shows the already assigned data as default but i cant access the selected data,

If i use,

<div ng-repeat="item in roleDataList">
        <input type="radio"  ng-model="$parent.parentRoleId"  ng-checked="item.RoleId==assignedRoleId?true:null" name="RoleRadioButton" ng-value="item"  />                   
       <span>{{item.RoleName}}</span>
</div>

then selected role is available in $parent.parentRoleId, but default value is not selected.

Any help where both can be achieved?


Solution

  • Check out this fiddle pretty much what you want i think

    Fiddle

    <div ng-controller="Ctrl">
    <span ng-repeat="category in categories">
      <label class="checkbox" for="{{category.id}}">
        <input type="checkbox" ng-model="selection.ids[category.id]" name="group" id="{{category.id}}" />
        {{category.name}}
      </label>
    </span>
    <pre ng-bind="selection.ids | json"></pre>    
    

    function Ctrl($scope) {
    
    $scope.selection = {
        ids: {"50d5ad": true}
    };
    
    $scope.categories = [ { "name": "Sport", "id": "50d5ad" } , {"name": "General", "id": "678ffr" } ];
    

    }