SrinivasAppQube SrinivasAppQube - 6 months ago 36
AngularJS Question

Object of array.length is not defined in angularjs

when i send the id to api. i got the response in object and consist of itemprice array. but object.itemprice.length is undefined. and object of itemprice undefined

//Controller:

ZustShopController.controller("ProductController",function($rootScope,$scope,DecreaseQuantitytService){
$scope.itemslist=DecreaseQuantitytService.DecreseQuantiyItem(item)
})

//Service:

ZustShopService.service("DecreaseQuantitytService",function(DecreaseQuantitytFactory){
this.DecreseQuantiyItem=function(item){
return DecreaseQuantitytFactory.DecreseAllQuantiyItem(item)
}
});

//Factory:

ZustShopFactory.factory("DecreaseQuantitytFactory",function($resource,RES_URL){

var iteminfo;
var itemresource=$resource(RES_URL+"product/:id/:itemcode",{"itemcode":"@itemcode"},{update:{method:"PUT"}})

return{
DecreseAllQuantiyItem:function(item){
iteminfo=itemresource.get({"itemcode": item.itemcode,"id":item.prevsubid});
return iteminfo;
}

})


Json Response

Resource {$promise: Promise, $resolved: false}
$promise:Promise
$resolved:true
__v:3
_id:"573f087078e73e28186a2fb7"
createdAt:"2016-05-20T12:52:00.897Z"
defaultmainprice:180
defaultofferprice:160
isDeleted:false
itemcode:"1000"
itemdescription:"Sun flower 1lit"
itemname:"Sun flower 1lit"
itemprice:Array[2]
modifiedAt:"2016-05-20T12:52:00.898Z"
status:false
subcatid:"5736aea0d3f55f3c155999a8"
unit:"1 lit"


$scope.itemslist.itemprice.length
is undefined

please help me how to do this

Answer

The problem is that your request is not resolved at the moment when you're checking it. You need to use Promise callback to assign loaded data to a scope variable.

ZustShopController.controller("ProductController",function($rootScope,$scope,DecreaseQuantitytService){
  DecreaseQuantitytService.DecreseQuantiyItem(item).then(function(data){
    $scope.itemslist = data;
  }
})

More on the Promises in $http service in angular and here.