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.

0

2 Answers 2

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]};
Sign up to request clarification or add additional context in comments.

1 Comment

It's a nice stable solution, thanks.
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>

1 Comment

Thanks, It is on spot solution/surgery , It's not possible to used it when we are not testing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.