AngryJS
AngryJS

Reputation: 955

$scope value not able to read in controller

I am not sure what is wrong with this but somehow not able to read correct value of $scope.

Here is my code at controller -->

$scope.verifyMobile = SearchFactory.verify.query({uuid: uuid});

The JSON returned by rest service is -->

 verifyNumber -- > {"id":1,"uuid":"2222","phoneNumber":"782941768355"}

I convert the POJO to JSON using gson.toString(verifyNumber Java class);

But when I try to check the value of phonenumber after making service call at controller, it always comes as undefined. can anybody please help. when I hardcode the value to returned JSON, it works fine but not with service.

 alert(JSON.stringify($scope.verifyMobile).uuid);

Upvotes: 0

Views: 57

Answers (1)

Claies
Claies

Reputation: 22323

You are not using $resource correctly. From the Angular Documentation for $resource:

The action methods on the class object or instance object can be invoked with the following parameters:

•HTTP GET "class" actions: Resource.action([parameters], [success], [error])

•non-GET "class" actions: Resource.action([parameters], postData, [success], [error])

•non-GET instance actions: instance.$action([parameters], [success], [error])

query() is a GET "class" action, so the correct call would be:

SearchFactory.verify.query({uuid: uuid}, function(data){
    //do something here on successful data retrieval
    $scope.verifyMobile = data;
}, function(){ 
   //do something here on failure
});

It's worth noting that the original call does actually work, but because it is an async call, what is being returned is the promise, not the actual data.

Also worth noting, the standardized HTTP actions for $resource look like the following:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

Therefore, you should consider using get instead of query when retrieving a single value, instead of modifying the query isArray property, whenever possible.

Upvotes: 1

Related Questions