Search code examples
angularjsselectng-options

AngularJS, Select and binding to value


I have a scenario that I thought it is logical, but seems angular doesn't support it.

So, I have in the scope/controller a list of user types as array of objects like this:

$scope.userTypes = [{text : "Buyer", value : "1"},
    {text : "Vendor", value :  "2"},
    {text : "Buyer / Vendor", value : "9"}];

$scope.user = new User(globalSelectedUserType);

Where the User is defined like this:

function User(userType) {
    this.userType = userType;
    this.isAdminUser = false;
    this.isActive = true;
    this.roleDisabled = true;
};  

And I want to have a select element with the list of options coming from the userTypes binding the values to the "value" property and text to the "text" property , and bind the select value to only the "value" property of the array object, allowing the user to set the value from the code.

so when I create the user from the code using this

$scope.user = new User("9");

it should initialize the select with the "Buyer / Vendor" selected.

Reading the documentation of the select element in angular and ng-options, seems it is impossible to do. I tried this

<select name="usertypedata" id="UsersTypeData" ng-model="user.userType"
          ng-disabled="user.roleDisabled" ng-options="usertype.value as usertype.text for usertype in userTypes track by usertype.value">
         </select>

and when we select the option, I want only the "value" property to be populated by the ng-model


Solution

  • I have two answers for this. First answer is what PSL suggested in his comments before. The second answer is

    instead of binding ng-options to an array, I bind it to an object and it worked fine

    to elaborate more, it might be that I am not doing fully angular solution from start to end. I am using angular to populate / and control the behavior of the html page / form.

    But later, I am doing normal html/form submit that will submit all the data inside the form. and usual form/submit, will use the select/option value to submit that value, and not ng-model

    but ng-model was important for me to select the option programmatically.