AngularJS - Set default value on select inside a ng-repeat [duplicate]

戏子无情 提交于 2019-11-29 06:10:47

I am not very much clear about your requirement but if you want to display a default selected value to <select>, you can use ng-selected. In order to use that you need to have default selected value in your controller as a model to your <select> and add ng-selected to your <options ng-selected="{{defaultvalue == value.id}}" ng-repeat="value in vatRates">

For code and reference i just altered your plunker,

http://embed.plnkr.co/ZXo8n0jE8r3LsgdhR0QP/preview

Hope this helps.

kachhalimbu

You should set the default value on the ng-model via controller instead of ng-init. From the docs

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

— AngularJS ng-init Directive API Reference - Overview

angular.module('app', [])
.controller('SelectController', function() {

    var selectCtrl = this;
  selectCtrl.values = ["Value 1", "Value 2", "Value 3"];
  selectCtrl.selectedValue = "Value 1";
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="SelectController as selectCtrl">
<select ng-model="selectCtrl.selectedValue"> 
  <option ng-repeat="value in selectCtrl.values" value="{{value}}">{{value}}     </option> 
  </select>
</div>
Chris

This is the only way i managed to do it, and its done when another select is changing. (maybe thats the cause other solutions don't work, please note the extra ""+ to force it to be a string. (otherwise not working)

In the controller:

$scope.formData.number_of_persons = "̲"̲+̲ $scope.numberOfPersons[0].val;

HTML:

<select name="number_of_persons" 
        id="number_of_persons" 
        ng-model="formData.number_of_persons" 
        required>
    <option ng-repeat="option in numberOfPersons" value="{{option.val}}">
        {{option.val}}
    </option>
</select>
Adam Michalski
<select ng-model="val" ng-init="myval = vals[0]">
    <option ng-repeat="myval in vals" value="{{myval.value}}">{{val.name}}
    </option>
</select>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!