2

我有一個像這樣的數組結構。AngularJS多個自動完成所需的範圍

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

我需要$範圍像下面爲我自動完成搜索。

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

任何人都可以幫助得到這個使用angularjs控制器。 在此先感謝。

回答

0

您可以使用地圖..

$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; 
    }); 
} 
+0

謝謝您的回答@Rakeschand ..!我會試試這個..! –

1

使用MAP

$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); 
+0

非常感謝@sisyphus .. !!它的工作..! –

1

你也可以創建一個輔助函數來爲你做這件事,而且你不必爲每個你想要的函數定義一張地圖,噸只是一個運行(因此僅僅快一點)這裏

樣品;)

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]}