2014-09-26 43 views
0

所以基本上我已經定義了以下選擇框:如何根據字段值不NG-模型對象選擇選項

<div ng-controller="ExampleController"> 
<span class="nullable"> 
    <select ng-model="myColor" ng-options="color.name for color in colors"> 
    <option value="">-- choose color --</option> 
    </select> 
</span><br/> 
<div> 
    <input type="button" value="Reinitialize array" ng-click="switchModel()"/> 
</div> 

而下面的控制器:

angular.module('selectExample', []) 
.controller('ExampleController', ['$scope', function($scope) { 
    $scope.colors = [ 
    {name:'black', shade:'dark'}, 
    {name:'white', shade:'light'}, 
    {name:'red', shade:'dark'}, 
    {name:'blue', shade:'dark'}, 
    {name:'yellow', shade:'light'} 
    ]; 
    $scope.myColor = $scope.colors[2]; // red 
    $scope.colorsB = [ 
    {name:'black', shade:'dark'}, 
    {name:'white', shade:'light'}, 
    {name:'red', shade:'dark'}, 
    {name:'blue', shade:'dark'}, 
    {name:'yellow', shade:'light'} 
    ]; 
    $scope.switchModel = function() { 
    $scope.colors = $scope.colorsB; 
    }; 
    }; 

}]); 

我遇到的問題是,如果在重新初始化陣列$scope.colors後如何選擇$scope.myColor中包含的選項作爲默認選項?

的plunker代碼是在這裏:http://plnkr.co/edit/50TVcrlxJHVH9kdEZljc?p=preview

+0

該值正在查看.name屬性,因此將其更改爲$ scope.colors [2] .name,它應該可以工作。 :) – 2014-09-26 18:12:40

+0

或者您可以將ngOptions更改爲ng-options =「color as color.name for color in colors」。 – 2014-09-26 18:13:43

+0

事情是我需要ng模型來引用對象$ scope.colors [2],由於其他原因,而不是在這個例子中的前奏 – 2014-09-26 18:15:51

回答

0

switchModel功能,再次更新模型如下圖所示。

$scope.switchModel = function() { 
     $scope.colors = $scope.colorsB; 
     $scope.myColor = $scope.colors[2]; 
     }; 

謝謝。

+0

不是我正在尋找的東西。我正在尋找一些選擇基於當前$ scope.myColor字段值的選項而不必重新初始化$ scope.myColor。 – 2014-09-26 18:49:51

0
$scope.switchModel = function() { 
     $scope.colors = $scope.colorsB; 
     //Reinit Your $scope.myColor 
     $scope.myColor = $scope.colors[2]; 
    }; 
+0

不是我在找什麼。我正在尋找一些將根據當前$ scope.myColor字段值選擇選項,而不必重新初始化$ scope.myColor。 – 2014-09-26 18:50:26