Vinicius de melo Vinicius de melo - 6 months ago 17
AngularJS Question

How do i store an array of objects with angularJS

i have this schema of a object in mongoDB, i will call my object CAR in this question:

this.carroSchema = new Schema({
modelo: String,
ano: String,
placa: String,
cor: String,
categoria: [{tipo: String, preco: String}],
createdOn: {type: Date, default: Date.now}
});


and i have this function that gets the object CAR and stores in the array 'arrayCarros'

$scope.carregarCarros = function(){
$http({
method: 'GET',
url: '/listaCarro'
})
.then(function successCallback(response){
$scope.arrayCarros = response.data;
}, function errorCallback(response){
alert(response.data);
});
}


if i do a select like this:

<select class="form-control" ng-click = "carregarCarros()" name="select">
<option ng-repeat = "carros in arrayCarros">{{carros.placa}}</option>
</select>


i have access to the propertie 'placa' from the object CAR, so i can show the values in my select.

but, my question is, how do i store the array 'categoria' that is inside of my object CAR, in other array so i can do a ng-repeat of him in my option and have access of his properties like 'tipo' and 'preco'?

Answer

Here is a simple way to do it. Obviously you could always use a built in javascript function like Array.filter or Array.reduce depending on your use case, but below is a simple to follow solution.

$scope.other_array = [];

response.data.forEach(function(car){
   $scope.other_array.push(car.categoria)
})

console.log(other_array)

It should also be noted you can have multiple ng-repeats and just have one render carros.place and one render carros.categoria. That or just have both vars rendered within the same ng-repeat.

Comments