如何使用angularJS存储对象数组

时间:2022-06-24 17:29:23

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

我在mongoDB中有一个对象的模式,我将在这个问题中调用我的对象CAR:

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'

我有这个函数,获取对象CAR并存储在数组'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.

我可以从对象CAR访问属性'placa',所以我可以在我的选择中显示值。

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

但是,我的问题是,我如何存储我的对象CAR内部的数组'categoria',在其他数组中,所以我可以在我的选项中对他进行重复 - 并且可以访问他的属性,如'tipo'和'PRECO'?

1 个解决方案

#1


0  

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.

这是一个简单的方法。显然你总是可以使用像Array.filter或Array.reduce这样的内置javascript函数,具体取决于你的用例,但下面是一个简单易懂的解决方案。

$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.

还应该注意,你可以有多个ng-repeats,只有一个渲染carros.place和一个渲染carros.categoria。那或者只是让两个变量在同一个ng-repeat中呈现。

#1


0  

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.

这是一个简单的方法。显然你总是可以使用像Array.filter或Array.reduce这样的内置javascript函数,具体取决于你的用例,但下面是一个简单易懂的解决方案。

$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.

还应该注意,你可以有多个ng-repeats,只有一个渲染carros.place和一个渲染carros.categoria。那或者只是让两个变量在同一个ng-repeat中呈现。