AngularJS 自动完成需要多个范围

AngularJS multiple Scope needed for Autocomplete

我有这样的数组结构。

[
  {
    "id": "1",
    "name": "John",
    "city": "NY"
  },
  {
    "id": "2",
    "name": "Gerold",
    "city": "LA"
  },
  {
    "id": "3",
    "name": "Stuart",
    "city": "Boston"
  }  
]

我需要像下面这样的 $scope 来进行自动完成搜索。

$scope.name=["john","Gerold","Stuart"];
$scope.city=["NY","LA","Boston"];

任何人都可以帮助使用 angularjs 控制器来获得它。 提前致谢!

您可以使用 MAP..

$scope.YourBigArray = [{
  "id": "1",
  "name": "John",
  "city": "NY"
}, {
  "id": "2",
  "name": "Gerold",
  "city": "LA"
}, {
  "id": "3",
  "name": "Stuart",
  "city": "Boston"
}];

$scope.names = $scope.YourBigArray.map(function(object) {
  return object.name;
});
$scope.cities = $scope.YourBigArray.map(function(object) {
  return object.city;
});

您可以做一个过滤器以在名称和城市数组中使用独特的东西。

function filterForDuplicate(things) {
  return things.filter(function(item, pos) {
    return things.indexOf(item) === pos;
  });
}

使用地图

$scope.users = [
  {
  "id": "1",
  "name": "John",
  "city": "NY"
  },
 {
  "id": "2",
  "name": "Gerold",
  "city": "LA"
 },
 {
   "id": "3",
  "name": "Stuart",
  "city": "Boston"
 }  
];

$scope.cities = $scope.users.map(function(obj){ 

 return obj.city;
});

console.log($scope.cities);

您还可以创建一个辅助函数来为您执行此操作,并且您不必为每个所需的函数定义一个映射,并且只需一个 运行(因此只需一个快一点)

示例在这里 ;)

var myArray = [
    {
        "id": "1",
        "name": "John",
        "city": "NY"
    },
    {
        "id": "2",
        "name": "Gerold",
        "city": "LA"
    },
    {
        "id": "3",
        "name": "Stuart",
        "city": "Boston"
    }
]
function toScope(scopedPropertieNames, array) {
    scopedPropertieNames.forEach(function(propertyName) {
        if (! $scope[propertyName]) {
            $scope[propertyName] = []
        }
    });
    array.forEach(function (objecInArray) {
        scopedPropertieNames.forEach(function(propertyName) {
            $scope[propertyName].push(objecInArray[propertyName])
        })
    });
}

toScope(['name', 'city'], myArray);
console.log($scope) //{name: Array[3], city: Array[3]}