简体   繁体   中英

angularjs select box set object value

this is my angular

angular.module("myApp",[])
.controller("myCtrl",function($scope){
  $scope.projectObj = {"proId":"33","proName":"samal"}
  $scope.projectArr = [{"proName":"samal","proId":"33"},{"proName":"aaa","proId":"47"},{"proName":"sdf","proId":"48"},{"proName":"sdf","proId":"49"},{"proName":"sddd","proId":"50"},{"proName":"dddd","proId":"51"},{"proName":"ttt","proId":"52"},{"proName":"sdf","proId":"53"},{"proName":"sdf","proId":"54"},{"proName":"sdf","proId":"55"},{"proName":"sdf","proId":"56"},{"proName":"sdf","proId":"57"},{"proName":"sdf","proId":"58"},{"proName":"sdf","proId":"59"},{"proName":"sdf","proId":"60"}]
})

this is my select box

<select ng-model="projectObj">
   <option value="{{item}}" ng-repeat="item in projectArr">{{item.proName}}</option>
</select>

$scope.projectObj is already assign with an object and it is already inside $scope.projectArr . what is want is when i load the html file $scope.projectObj proName should be pre-selected.how can i do this. this is my pluker

Repeating options isn't preferred way to show select dropdown. I'd suggest you to to use ng-options directive to get object binding on ng-model

<select  flex ng-model="projectObj" 
  ng-options="item as item.proName for item in projectArr">
</select> 

And then assign projectObj from projectArr .

$scope.projectObj  = $scope.projectArr[0];

Demo here


Use md-select for Angular material like below and use ng-model-options="{trackBy: '$value.proId' for directly pre select object. Additionally you have to follow Dot Rule while defining ng-model

Markup

<md-input-container>
  <md-select ng-model="projectObj" placeholder="Select a state"
    ng-model-options="{trackBy: '$value.proId'}">
    <md-option ng-value="item" ng-repeat="item in projectArr">
      {{ item.proName }}
    </md-option>
  </md-select>
</md-input-container>

CodePen

You can use ng-selected. This will work.

<option value="{{item}}" ng-selected="item" ng-repeat="item in projectArr">{{item.proName}}</option>

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