2016-01-03 97 views
1

http://plnkr.co/edit/knmWulxhKdeQoMVm7u4k?p=preview與NG-選擇和NG-重複AngularJS奇怪的行爲

<!doctype html> 
<html lang="en"> 

<head> 
    <meta charset="UTF-8"> 
    <title>Example - example-static-select-production</title> 


    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script> 
    <script src="app.js"></script> 



</head> 

<body ng-app="staticSelect"> 

    <select name="quarter" ng-model="Quarter"> 
    <option ng-repeat="v in [1,2,3,4]" ng-selected="v==4">Q{{v}}</option> 
    </select> 

    <select name="quarter" ng-model="Quarter"> 
    <option ng-repeat="v in [1,2,3,4]" value="{{v}}" ng-selected="v==3">Q{{v}}</option> 
    </select> 

</body> 

</html> 

ng-selected似乎只能選擇最後一個元素。爲什麼是這樣?

我檢查了元素,並且ng-selected標記爲true。但是,如果它不是最後一個元素,那麼它最初不會被選中。

+0

你想要實現什麼? – Sajeetharan

+0

你好,這是我的問題的簡化版本。基本上我有一個選擇標籤的json數組。我想將選項標記初始化爲從數據庫中檢索的JSON。 – Zanko

回答

1

你可以試試這個代碼,

<select name="quarter" ng-model="Quarter" ng-options="item as 'Q'+item for item in [1,2,4,3]"> 

在你的控制器,你必須指定 「季」,如:

$scope.Quarter = 3 

這是一個完整的例子:

(function(angular) { 
 
    'use strict'; 
 
angular.module('staticSelect', []) 
 
    .controller('ExampleController', ['$scope', function($scope) { 
 
    $scope.data = { 
 
    singleSelect: null, 
 
    multipleSelect: [], 
 
    option1: 'option-1', 
 
    }; 
 

 
    $scope.Quarter = 3; 
 
    
 
    $scope.forceUnknownOption = function() { 
 
     $scope.data.singleSelect = 'nonsense'; 
 
    }; 
 
}]); 
 
})(window.angular); 
 
<!doctype html> 
 
<html lang="en"> 
 

 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>Example - example-static-select-production</title> 
 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script> 
 
    
 
</head> 
 

 
<body ng-app="staticSelect" ng-controller="ExampleController"> 
 

 
    <select name="quarter" ng-model="Quarter" ng-options="item as 'Q'+item for item in [1,2,3,4]"> 
 
</body>  
 
</html>