简体   繁体   中英

Angular.js: How do I initialize the ng-model of a <select> element to be the ng-selected option's value?

My select looks like this:

<select ng-model="model.string">
     <option ng-repeat="option in options"
             ng-bind-html="option.name"
             ng-selected="option.name === 'Selected Option'"
             ng-value="option.value">
     </option>
</select>

There is no way of knowing which options's name is 'Selected Option' and I cant use ng-options. So this and this does not solve my problem.

What can I do for model.string to be the value of the initially selected value instead of undefined or whatever it was initialized as?

EDIT: plunker

Use ng-options and it will automatically select the value present in ng-model .

If this doesn't work for you, please add more details like your JS code specially, your ng-model object.

A fiddle or plunker would be best.


Since you are so keen in using ng-repeat and not ng-options , here is how you can achieve it:

In your controller add the below code:

$scope.model={};

for(var i=0;i<$scope.options.length;i++){
  var selectedOption = $scope.options[i].selected;
  if(selectedOption != null && selectedOption == "selected"){
    $scope.model.string = $scope.options[i].name
  }
}

Updated Plunker: http://plnkr.co/edit/V6ogGyksHlAWrgtDhkMU?p=preview

If you don't use ng-options, you'll have to initialize your model "by yourself", getting the value selected in your options collection :

 $scope.getChosenOption = function()
 {
   for (var i in $scope.options)
    if ($scope.options[i].selected === 'selected')
     return $scope.options[i].name;
 };

$scope.selected = $scope.getChosenOption();

Plus, I think you made a typo using "model.string" in your view instead of "selected" $scope variable.

Here is your Plunker updated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM