0

<select>要素をスコープの一部のオプションであらかじめ入力する必要があり、最初に選択されるモデルとして値がバインドされるようにします。ng-optionsをモデル値に初期化する

問題は、モデル値が選択されておらず、代わりに空白の要素が作成されて選択されていることです。

JSONモデル

var fruits = { 
    "0":"apple", 
    "1":"pear", 
    "2":"banana" 
} 

コントローラ

$scope.items = fruits; 
$scope.myfruit = 1; // also tried "1" 

テンプレートマークアップ:

<select class='form-control' name="fruit" 
    ng-model="myfruit"    
    ng-options="key as val for (key, val) in items" >      
</select> 

ドロップダウン私nuはすべての値をレンダリングし、意図したとおりにキーでモデルを更新しますが、最初の要素は選択された空の項目です。

ただし、オプションを選択すると、空のオプションは表示されなくなります。

私も同じ結果とng-repeatを使用してマークアップを書いてみました:

<select class='form-control' name="fruit" 
    ng-model="myfruit" > 
    <option ng-repeat="(k, val) in items" value="{{k}}">{{val}}</option>       
</select> 

はどのようにして、初期化時にモデルで表される値が選択されるように得ることができますか?

+1

それは私のために働いています: '$ scope.myfruit =「1'' –

+0

はいああ。それはうまくいった。私は私のモデルを文字列に変換しなければならないと思う – yevg

答えて

1

オプション値は文字列です

これは動作するはずです。

$scope.myfruit = "1"; 

チェック以下の実施例

var app = angular.module('plunker', []); 
 

 
app.controller('MainCtrl', function($scope) { 
 

 
    var fruits = { 
 
    "0": "apple", 
 
    "1": "pear", 
 
    "2": "banana" 
 
    } 
 

 
    $scope.items = fruits; 
 
    $scope.myfruit = "1"; 
 

 

 
});
<!DOCTYPE html> 
 
<html ng-app="plunker"> 
 

 
    <head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    <script>document.write('<base href="' + document.location + '" />');</script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script> 
 
    <script src="app.js"></script> 
 
    </head> 
 

 
    <body ng-controller="MainCtrl"> 
 
    
 
    <select class='form-control capitalize' name="cost" 
 
    ng-model="myfruit"    
 
    ng-options="key as val for (key, val) in items" >      
 
    </select> 
 
    
 
    
 
    </body> 
 

 
</html>

関連する問題