Shnigi
Shnigi

Reputation: 1002

Angularjs radio selection as checked

I am trying to create selection when new user is created it will need a group. It is working nicely, but the "checked" option doesn't work for some reason. How can I make the "user" as checked so it would be true if create new user button is pressed?

 <div class="radio-group" required>
      <h3>Set user group</h3>
    <label class="radio-inline">
      <input type="radio" name="groupradio" value="2" ng-model="groups.group" required> Admin
    </label>

    <label class="radio-inline">
      <input type="radio" name="groupradio" value="1" ng-model="groups.group" checked> User
    </label>

    <label class="radio-inline">
      <input type="radio" name="groupradio" value="3" ng-model="groups.group"> Viewer
    </label>
    </div>
  <button class="btn-sonera" ng-click="createUser(user, groups)"><i class="fa fa-floppy-o" aria-hidden="true"></i> Create user</button>

Upvotes: 0

Views: 84

Answers (4)

ciril sebastian
ciril sebastian

Reputation: 549

Could you please try by using ng-value

 <label>
    <input type="radio" ng-model="groups.group" value="1">
    Admin
  </label><br/>
  <label>
    <input type="radio" ng-model="groups.group" value="2">
    User
  </label><br/>
  <label>
    <input type="radio" ng-model="groups.group" value="3">
    Viewer
  </label><br/>

in controller

 $scope.createUser = function(user, groups){
        groups.group = "2";

      };

Upvotes: 0

Shnigi
Shnigi

Reputation: 1002

I managed to make it checked with ng-init="groups.group=1" Because I need the value assigned to the radio. Is there something wrong using it this way?

Full code

<div class="radio-group" required>
  <h3>Set user group</h3>
<label class="radio-inline">
  <input type="radio" name="groupradio" value="2" ng-model="groups.group" required> Admin
</label>

<label class="radio-inline">
  <input type="radio" name="groupradio" value="1" ng-model="groups.group" ng-init="groups.group=1"> User
</label>

<label class="radio-inline">
  <input type="radio" name="groupradio" value="3" ng-model="groups.group"> Viewer
</label>
</div>

Upvotes: 1

terpinmd
terpinmd

Reputation: 1028

Here is a working plunker: https://plnkr.co/edit/4VtblBSWROLTETW5Ie5C?p=preview

The core code:

  $scope.groups = {
    admin : false, 
    user: false, 
    viewer: false
  };

And in the view:

<button class="btn-sonera" ng-click="groups.user=true"><i class="fa fa-floppy-o" aria-hidden="true"></i> Create user</button>

Note how each ng-model is bound to an object, ie: groups.admin, groups.user etc.

Upvotes: 0

Maciej Sikora
Maciej Sikora

Reputation: 20132

With AngularJs best is use its directive:

ng-checked="variable"

Upvotes: 1

Related Questions