2017-06-06 71 views
0

我想要獲取json對象的每個屬性,以創建一個下拉列表。下拉列表選擇一個過濾器

我要解釋一下,例如:

我有2個JSON對象:

{"name":"Paul","age":"18","sport":"Basket","color":"Green"} 
{"name":"Jhon","age":"20","sport":"Basket","fruit":"banana", "number":"5"} 

我有內{name,age,sport,color,fruit,number}的下拉列表。 如果我選擇姓名,我在{Paul,Jhon}內有第二個下拉列表。

我使用AngularJS,Node.js的

我知道,每次得到的屬性後,我要申請單一性過濾器,只有型動物屬性,但不是的發生

回答

1

假設ES6是好的,我們可以用Set返回唯一值(如果沒有 - 你可以使用some other techniques to get an array with unique elements),可以使用ngChange directive檢測的第一選擇和填充選項進行更改爲第二選擇。因此,控制器和標識看上去象這樣:

angular.module('myApp', []) 
 
.controller('MyCtrl', function MyCtrl($scope) { 
 
    var ctrl = this; 
 

 
    var data = [ 
 
    {"name":"Paul","age":"18","sport":"Basket","color":"Green"}, \t 
 
    {"name":"Jhon","age":"20","sport":"Basket","fruit":"banana", "number":"5"}, 
 
    {"name":"Mark","age":"22","sport":"Football","color":"Red", "number":"5"} \t 
 
    ]; 
 

 
    ctrl.objKeys = getUniqueKeys(data); 
 
    ctrl.objVals = []; 
 
    ctrl.keyChanged = keyChanged; 
 

 
    function keyChanged(key) { 
 
    ctrl.objVals = getUnique(data.map(function(obj) { return obj[key] }).filter(function(obj) { return !!obj; })); //get the values and filter only the ones are defined 
 
    } 
 

 
    function getUnique(arr) { 
 
    return [...new Set(arr)]; //get array with unique values 
 
    } 
 

 
    function getUniqueKeys(arr) { 
 
    return getUnique([].concat.apply([], arr.map(function(obj) { return Object.keys(obj); }))); //get the property names 
 
    } 
 

 
    return ctrl; 
 
});
<script src="//code.angularjs.org/1.6.2/angular.js"></script> 
 
<div ng-app="myApp"> 
 
    <div ng-controller="MyCtrl as $ctrl"> 
 

 
    <select ng-model="objKey" ng-change="$ctrl.keyChanged(objKey)" 
 
    ng-options="k for k in $ctrl.objKeys track by k"></select> 
 

 
    <select ng-if="$ctrl.objVals.length" ng-model="objVal" 
 
    ng-options="k for k in $ctrl.objVals track by k"></select> 
 

 
    </div> 
 
</div>

0

可能不是完美的,但這是工作

HTML:

<div ng-controller="MyCtrl"> 
     <select ng-model="selectedItem" ng-change="itemChanged()" ng-options="item for item in list1"> 
     </select> 
     <select ng-model="second" ng-options="lst for lst in list2 "></select> 

</div> 

控制器:

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

myApp.controller('MyCtrl', function MyCtrl($scope) { 
$scope.list1 = ["name","age","sport","color","fruit","number"]; 
$scope.data = [{"name":"Paul","age":"18","sport":"Basket","color":"Green"},{"name":"Jhon","age":"20","sport":"Basket","fruit":"banana", "number":"5"}]; 
    $scope.itemChanged = function() { 
    var prop = $scope.selectedItem;  
    $scope.list2 = []; 
    $scope.data.forEach(x => { 
    if(x[prop] && $scope.list2.indexOf(x[prop])) { 
     $scope.list2.push(x[prop]); 
    }  
    }); 
    }; 
}); 

的jsfiddle演示:http://jsfiddle.net/sathvike/vzzmrnvL/