2017-01-25 15 views
0

私はAngularjsの学習を始めました。私はw3schoolsのチュートリアルに従っていたので、何かを試してみる必要がありました。ラジオボタンに従って選択を更新してください

ここでは、チェックしたラジオボタンに従ってドロップダウンリストを表示します。 (「名前」を選択すると、ドロップダウンリストに名前だけが必要です。都市を選択すると、「都市」ドロップダウンリストなどが必要です)。

<body ng-app="myApp" ng-controller="myController"> 
    <div> 
     <input type="radio" ng-model="selection" value="Name">Name 
     <input type="radio" ng-model="selection" value="Country">Country 
     <input type="radio" ng-model="selection" value="City">City 
     <br> 
     <div ng-switch="selection"> 
     <div ng-switch-when="Name"> 
     <ul> 
      <li ng-repeat="x in names">{{x.Name}}</li> 
     </ul> 
     </div> 
     <div ng-switch-when="Country"> 
     <ul> 
      <li ng-repeat="x in names">{{x.Country}}</li> 
     </ul> 
     </div> 
     <div ng-switch-when="City"> 
     <ul> 
      <li ng-repeat="x in names">{{x.City}}</li> 
     </ul> 
     </div> 
     </div> 
     <br> 
     <select ng-model="selectedName" ng-options="x.Name for x in names"></select> 
    </div> 
    </body> 

これは角度のあるスクリプトファイルです。

var app = angular.module('myApp',[]); 
    app.controller('myController', function($scope,$http){ 
     $http.get('http://www.w3schools.com/angular/customers.php') 
    .then(function(response){ 
     $scope.names = response.data.records; 
     }); 
    }); 

答えて

0

私はあなたが条件付きでng-model="selection"ラジオ入力項目からの選択に基づいてラベルを表示したいあなた<select>要素について、正しく理解していた場合。あなたは反復されている項目だけでなく、ラジオの入力から選択両方を渡し選択に基づいてラベルのプロパティをターゲットに、あなたのng-options内の機能を使用することができます。

JS:

$scope.foo = function(x, selection) { 
    switch(selection) { 
    case 'Name': 
     return x.Name; 
     break; 
    case 'City': 
     return x.City; 
     break; 
    case 'Country': 
     return x.Country; 
    default: 
     return x.Name; 
    } 
} 

HTML :ここでは

<select ng-model="selectedName" ng-options="x.Name as foo(x, selection) for x in names"></select> 

は条件付きラベルのドロップダウン表示のための機能を利用as構文でng-optionsを示すPlunkerあります。

うまくいけば助けてください!

+0

ありがとう。これが私の必要なものです。 –

0

あなたはng-repeatを組み合わせて、オプションでフィルタを使用できます。

HTML

  <select class="form-control" ng-model="selectedName"> 
       <option value="" selected disabled>Select Name</option> 
       <option ng-repeat="n in names" value="{{n.Name}}">{{n.Name | filter:isSelection('Name')}}</option> 
       <option ng-repeat="n in names" value="{{n.Country}}">{{n.Country| filter:isSelection('Country')}}</option> 
       <option ng-repeat="n in names" value="{{n.City}}">{{n.City| filter:isSelection('City')}}</option> 
      </select> 

JS

$scope.isSelection = function(x){ 
    return x == $scope.selection; 
} 

ng-repeatはそれが選択の種類の文字列でフィルタを使用します。これは、同じでないオプションを除外します。selection

関連する問題