2013-07-15 42 views
0

的選擇設置所選的選項我有如何在角

$scope.colleges = [{"CollegeCode":"40","CollegeName":"College1"}, 
{"CollegeCode":"35","CollegeName":"College2"}, 
{"CollegeCode":"32","CollegeName":"College3"}, 
{"CollegeCode":"15","CollegeName":"College4"}] 

我填充一個選擇的元素與它的內容

<select ng-model="collegeSelection" ng-options="c as c.CollegeName for c in colleges" name="selectCollege"></select> 

它呈現在網頁上像這樣

對象
<select class="ng-pristine ng-valid" name="selectCollege" ng-options="c as c.CollegeName for c in colleges" ng-model="collegeSelection" style="" selected="selected"> 
<option value="?" selected="selected"></option> 
<option value="0">College1</option> 
<option value="1">College2</option> 
<option value="2">College3</option> 
<option value="3">College4</option> 
etc.... 

我也將這個select綁定到collegeSelection,當一個項目被選中時,對象看起來像這樣

$scope.collegeSelection = {"CollegeCode":"32","CollegeName":"College"} 

當有人點擊頁面上的編輯時,我想要默認選擇的學院來自userToUpdate對象。

$scope.userToUpdate = { 
      Id: 1, 
      FirstName: 'John', 
      LastName: 'Doe', 
      CollegeCode: '35, 
      CollegeName: 'College2', 
      Active: true 
     }; 

當填充編輯按鈕和userToUpdate對象,我想在選擇元件學院被設置爲在用戶對象的大學。一個人怎麼能做到這一點?僅供參考,呈現的select中的值與CollegeCode不匹配。看起來角度使用來自高校對象的索引。由於

回答

1

試試這個

<select ng-model="collegeSelection" ng-options="c.CollegeCode as c.CollegeName for c in colleges" name="selectCollege"></select> 
    <span>{{collegeSelection}}</span> 
    <input type="button" ng-click="switch()" name="switch" value="switch" /> 
    <script> 
     var app = angular.module('plunker', []); 

     app.controller('MainCtrl', function ($scope, $filter) { 
      $scope.colleges = [{ "CollegeCode": "40", "CollegeName": "College1" }, 
           { "CollegeCode": "35", "CollegeName": "College2" }, 
           { "CollegeCode": "32", "CollegeName": "College3" }, 
           { "CollegeCode": "15", "CollegeName": "College4" } 
      ] 

      $scope.switch = function() { 
       $scope.collegeSelection = "32"; 
      }; 
     }); 
+0

此方法更新collegeSelection對象,但由於某些原因,它不更新實際選擇的元素(選擇collegecode 35時,「不選擇顯示College2。 – rross

+1

請檢查一下是否有效plnkr.co/edit/bejp3iAG7Z15gFjd5lDF?p=preview –