angularjs选择框设置对象值

时间:2016-07-29 09:19:57

标签: javascript angularjs

这是我的角色

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"}]
})

这是我的选择框

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

$ scope.projectObj 已经分配了一个对象,它已经在 $ scope.projectArr 中。我想要的是当我加载html文件时,应该预先选择$ scope.projectObj proName。我可以这样做吗?这是我的pluker

2 个答案:

答案 0 :(得分:1)

重复options不是显示选择下拉列表的首选方式。我建议您使用ng-options指令在ng-model

上获取对象绑定
<select  flex ng-model="projectObj" 
  ng-options="item as item.proName for item in projectArr">
</select> 

然后从projectObj分配projectArr

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

Demo here

md-select用于下面的Angular素材,并使用ng-model-options="{trackBy: '$value.proId'直接预选对象。此外,您必须在定义Dot Rule

时关注ng-model

<强>标记

<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

答案 1 :(得分:0)

您可以使用ng-selected。这将有效。

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