下拉列表选择过滤器

时间:2017-06-06 13:51:18

标签: javascript angularjs json node.js

我试图获取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

我知道在获得每个属性后我必须应用unicity过滤器,只有不同的属性而不是出现

2 个答案:

答案 0 :(得分: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"},	
    {"name":"Jhon","age":"20","sport":"Basket","fruit":"banana", "number":"5"},
    {"name":"Mark","age":"22","sport":"Football","color":"Red", "number":"5"}	
  ];

  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>

答案 1 :(得分: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/