2017-03-28 7 views
1

ng-modelを使用するドロップダウンボックスで問題が発生していて、ドロップダウンを使用できる状態でドロップダウンのインデックスを変更しています。変更時に空の選択にリセットするドロップダウンボックスの問題

たとえば、このコード(http://jsfiddle.net/Q5hd6/357/)を使用してドロップダウンのインデックスを変更できます。しかし、インデックスを変更するとデフォルトで空の選択に戻り、他のものを選択することはできません。

HTML:

<select ng-model="RecievedSelect" ng-options="item.id as item.name for item in RecievedOptions"></select> 
<button ng-click="ChangeIndex()">Change index</button> 

JS:

$scope.RecievedOptions = [ 
           {id : 0, name: "No"}, 
           {id : 1, name: "Yes"} 
          ]; 

    $scope.ChangeIndex = function() 
    { 
     $scope.RecievedSelect = $scope.RecievedOptions[0]; 
    } 

しかし、私はtrack by item.idを削除する場合、私は手動でインデックスを変更することができるんだけど、もはやボタン(http://jsfiddle.net/Q5hd6/358/)でそれらを変更することはできません。

基本的に、私は両方をしたいと思っていますが、次はどこに行くのか分かりません。

答えて

2

選択要素のモデルには選択されたオプションの値が含まれているため、$scope.RecievedSelect = $scope.RecievedOptions[0].id;にする必要があります。

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

 
myApp.controller('MyCtrl', function($scope) { 
 
    $scope.RecievedOptions = [ 
 
          {id : 0, name: "No"}, 
 
          {id : 1, name: "Yes"} 
 
          ];       
 
    $scope.ChangeIndex = function() { 
 
     $scope.RecievedSelect = $scope.RecievedOptions[0].id; 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="MyCtrl"> 
 
<select ng-model="RecievedSelect" ng-options="item.id as item.name for item in RecievedOptions"></select> 
 
<button ng-click="ChangeIndex()">Change index</button> 
 
</div>

+0

今多くの意味をなします。私は選択されたブールを上書きしているとは考えていませんでした。ありがとうございました! –

1

AngularJs docに述べたように、それは新しいスコープを作成していないので、これはNG-オプションの場合に動作しますが、私の言葉の残りの部分は、NG-モデルディレクティブのために有効であり、いかなる新しいスコープを作成するディレクティブです(配列内の各アイテムのng-repeatの場合、新しい子スコープが作成されます)。このメカニズムについてはUnderstand the concept of scopesを読むことができますが、それは常に正しいパターンです。

オブジェクトを通過しないと、子スコープはここで独自の値を作成します。ReceivedSelectこれはJavaScriptの動作で、sct.ReceivedSelectのようなオブジェクトの属性に変更する必要があります。

<div ng-app="myApp" ng-controller="MyCtrl"> 

<select ng-model="sct.RecievedSelect" ng-options="item as item.name for item in RecievedOptions track by item.id"></select> 
<button ng-click="ChangeIndex()">Change index</button> 
</div> 

JS:

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

myApp.controller('MyCtrl', function ($scope) { 
$scope.RecievedOptions = [ 
           {id : 0, name: "No"}, 
           {id : 1, name: "Yes"} 
          ]; 
    $scope.sct = {RecievedSelect : $scope.RecievedOptions[0]};         
    $scope.ChangeIndex = function() { 
    $scope.sct.RecievedSelect = $scope.RecievedOptions[0]; 
    } 
}); 

このJSFiddleに見てみましょう:

http://jsfiddle.net/Q5hd6/367/

関連する問題