简体   繁体   中英

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'?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM