简体   繁体   English

如何使用angularJS存储对象数组

[英]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: 我在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”存储在其他数组中,以便我可以对他进行ng-repeat选择并访问其属性(如“ tipo”和'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. 显然,根据您的用例,您始终可以使用内置的javascript函数(例如Array.filter或Array.reduce),但是以下是易于遵循的解决方案。

$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. 还应该注意的是,您可以具有多个ng-repeats,并且只有一个渲染carros.place和一个渲染carros.categoria。 That or just have both vars rendered within the same ng-repeat. 那个或只是两个var在同一个ng-repeat中呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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