2017-02-09 47 views
1

如何使用ng-option在選擇倍數='倍數'中設置默認值? 我一直在嘗試兩種方法,請看下面的代碼:如何使用(鍵值)設置ng選項倍數的默認值

angular.module('ngrepeatSelect', []).controller('ExampleController', ['$scope', function ($scope) { 
 
\t $scope.o1 = {"de":"Deutsch", 
 
\t "en":"English","es":"Español", 
 
\t "fl":"Flemish","fr":"Français", 
 
\t "it":"Italiano","nl":"Nederlands", 
 
\t "pl":"Polski", 
 
\t "pt":"Português", 
 
\t "ro":"Română", 
 
\t "tr":"Türkçe"}; 
 
\t $scope.o2 = { 
 
\t \t "it":{"prefix":"it","label":"Italiano"}, 
 
\t \t "fr":{"prefix":"fr","label":"Français"}, 
 
\t \t "es":{"prefix":"es","label":"Español"}, 
 
\t \t "fl":{"prefix":"fl","label":"Flamand"}, 
 
\t \t "en":{"prefix":"en","label":"English"}, 
 
\t \t "de":{"prefix":"de","label":"Deutsch"}, 
 
\t \t "pt":{"prefix":"pt","label":"Português"}, 
 
\t \t "ro":{"prefix":"ro","label":"Română"},"pl":{"prefix":"pl","label":"Polski"}, 
 
\t \t "tr":{"prefix":"tr","label":"Türkçe"}, 
 
\t \t "nl":{"prefix":"nl","label":"Nederlands"}}; 
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> 
 
<div ng-app="ngrepeatSelect"> 
 
\t <div ng-controller="ExampleController"> 
 
\t \t <div> 
 
\t \t \t <select 
 
\t \t \t \t \t ng-init="selected1 = 'fr'" 
 
\t \t \t \t \t multiple="multiple" 
 
\t \t \t \t \t ng-model="selected1" 
 
\t \t \t \t \t ng-options="key as value for (key, value) in o1 track by key"> 
 
\t \t \t </select> 
 
\t \t \t <select 
 
\t \t \t \t \t ng-init="selected2 = 'fr'" 
 
\t \t \t \t \t multiple="multiple" 
 
\t \t \t \t \t ng-model="selected2" 
 
\t \t \t \t \t ng-options="language.prefix as language.label for language in o2 track by language.prefix"> 
 
\t \t \t </select> 
 
\t \t </div> 
 
\t \t <div> 
 
\t \t \t -{{selected1}}- 
 
\t \t \t -{{selected2}}- 
 
\t \t </div> 
 
\t </div> 
 
</div>

例如,如何預選「德」,「FR」和「RO」中爲每一個選擇的? 謝謝!

+0

你試過'NG-selected'? –

+0

不是,但我會,謝謝。但是,Slava.K找到了解決方案。 – Pierre

回答

0

只需在控制器中預先填充selected1即可。此外,它看起來像track by key已過時,可以刪除。找到下面的工作片段:

angular.module('ngrepeatSelect', []).controller('ExampleController', ['$scope', function ($scope) { 
 
    $scope.selected1 = ["de", "fr", "ro"]; 
 
\t 
 
    $scope.o1 = {"de":"Deutsch", 
 
\t "en":"English","es":"Español", 
 
\t "fl":"Flemish","fr":"Français", 
 
\t "it":"Italiano","nl":"Nederlands", 
 
\t "pl":"Polski", 
 
\t "pt":"Português", 
 
\t "ro":"Română", 
 
\t "tr":"Türkçe"}; 
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> 
 
<div ng-app="ngrepeatSelect"> 
 
    <div ng-controller="ExampleController"> 
 
    <div> 
 
\t <select 
 
\t multiple="multiple" 
 
\t ng-model="selected1" 
 
\t ng-options="key as value for (key, value) in o1"> 
 
\t </select> 
 
    </div> 
 
    <div> 
 
     -{{selected1}}- 
 
    </div> 
 
    </div> 
 
</div>

+0

確實有用,非常感謝! – Pierre