0

I am almost new to AngularJS, and I am using a select tag for selection . What I want is to have a default value (i.e admin) for my select tag to define the role of my user which are agent and admin

Here is my HTML codes:

<div class="row">
    <div class = "form-group col-xs-12 col-md-6">
        <label>
            Role 
        </label>
        <select class="form-control" ng-options="value for value in roles" ng-model="newStaff.role_name='agent'"></select>
    </div>
</div>

and here is my controller codes:

controllers.controller('StaffMembersNewCtrl', function ($scope, StaffMembers, $state) {
    $scope.roles = ['admin', 'agent'];
    StaffMembers.query(function(responce) {
        $scope.staffs = responce;
    });
    $scope.SaveNewStaffMember = function(){
        StaffMembers.save($scope.newStaff, function(){
        $scope.addAlert('success', 'New staff member was added successfully!');
        $state.go('staffMembersSettings');
     });
    };
});

It seems working, I have a default value, and data is bind, but there is an error in browser.

Error: [ngModel:nonassign] Expression 'newStaff.role_name='agent'' is non-assignable. Element: <select class="form-control ng-pristine ng-untouched ng-valid" ng-options="value for value in roles" ng-model="newStaff.role_name='agent'">

I understand this error, but I can not find an alternative solution for my problem which is putting a default value for my select tag.

David Spence
  • 7,999
  • 3
  • 39
  • 63
Ali Saberi
  • 864
  • 1
  • 10
  • 33

2 Answers2

1

You can define your default in JS or HTML. The way you're trying to use ng-model suggests you want to define the default in HTML. ng-init would be one way to do that (you're actually using ng-model the way one would use ng-init). Think of ng-model as a kind of "address" that points angular to WHERE you want to store the selection, not WHAT you want to store in there.

Since your data model is in JS, I suggest you do it there instead so that you can reference the appropriate role name in $scope.roles

HTML

<select class="form-control" ng-options="value for value in roles" ng-model="newStaff.role_name"></select>

CONTROLLER

$scope.newStaff = {role_name: $scope.roles[0]};
HankScorpio
  • 3,612
  • 15
  • 27
0

Try this..

<div class="row">
    <div class = "form-group col-xs-12 col-md-6">
        <label>
            Role 
        </label>
        <select class="form-control" ng-options="value for value in roles" ng-model="newStaff.role_name" ng-init="newStaff.role_name=roles[1]"></select>
    </div>
</div>
Ritt
  • 3,181
  • 3
  • 22
  • 51