UTSAV BHAGAT UTSAV BHAGAT - 5 months ago 11
Node.js Question

showing information of referenced schemas using angular

I have 2 schemas as follows:

In Product, I have an array of Elements separated by comma (,)

The Element Schema defines each element inside the Elements field in Product

var Product = new Schema({

name: {type: String},
Elements: {type : String}
});

var Element= new Schema({

title: {type: String},
code : {type : String}
});


HTML file:

<div class="productController as product">
<div ng-repeat="pro in product.product.Elements.split(', ')" ng-init="getCategory(pro)">
<h3>{{pro}} {{data.code}}</h3>
</div>
</div>


In productController

productid = $routeParams.id;
var getthatProduct = function(){
productFactory.getthatProduct(productid, function(data){
console.log('[CONTROLLER] That Product:',data);
that.product = data;

})
}
getthatProduct();

$scope.getCategory = function(data){

elementFactory.getElements(data, function(data){
console.log('[CONTROLLER] That Element:',data);
$scope.data = data;

})
}


elementFactory:

factory.getElements= function(data, callback){
$http({
url:'api/seeelements',
method:'GET',
params:{title: data}
}).then(function(response){
//console.log(data);
callback(response.data)
})
}


getElements is defined in my factory which fetch all the elements info from Element Schema

I can fetch {pro} but i'm not able to fetch the element info.

How to display the Element.title for each element in a single product ?

Answer

My recommendation, don't use ng-init. Get elements, create a hash and use it then.

productid = $routeParams.id;
$scope.elementsHash={};
$scope.productElements = [];
var getthatProduct = function(){
    productFactory.getthatProduct(productid, function(data){
        console.log('[CONTROLLER] That Product:',data);
        that.product = data;
        $scope.productElements = that.product.product.Elements.split(', ');
        $scope.productElements.forEach(function(elem){
            $scope.getCategory(elem); //get each element's info
        }); 
    })
}
getthatProduct();

$scope.getCategory = function(data){

elementFactory.getElements(data, function(resp){
        console.log('[CONTROLLER] That Element:',resp);
        $scope.elementsHash[data] = resp; //this will update the hashes e.g {'sometitle':{title:'sometitle',code:123}}
    })
}

now in your html, use that hash

<div class="productController as product">
    <div ng-repeat="pro in productElements">
        <h3>Element title: {{pro}}</h3>
        <p>{{elementsHash[pro].code}}</p> <!-- e.g. elementsHash.sometitle.code
    </div>
</div>

Hope this helps

Comments