LadyT
LadyT

Reputation: 659

Angularjs $resource: How do I get the specific data from inside the json object?

This is my first time using Angularjs $resource and I am trying to do some testing on my application. I am trying access one of the properties instead of showing the entire object. How can I access data.image or data.url?

json data from weather underground

   {
   "response": {
   "version":"0.1",
    "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
    "features": {
    "conditions": 1
   }
   }
   ,    "current_observation": {
    "image": {
    "url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png",
    "title":"Weather Underground",
    "link":"http://www.wunderground.com"
    },
    "display_location": {
    "full":"San Francisco, CA"
    }

weather factory

app.factory('weatherService',['$resource', function($resource){
var factory={};
 factory.getWeather = function(){
     return $resource("http://api.wunderground.com/api/9eb7777065b59c55/conditions/q/CA/San_Francisco.json").get();
 }
return factory;
}]);

weather controller

 app.controller('weather', ['$scope', '$http','weatherService',   function($scope, $http, weatherService){
 $scope.weather = weatherService.getWeather().get();
 }]);

Upvotes: 0

Views: 434

Answers (2)

atefth
atefth

Reputation: 1623

Your implementation of $resource is wrong, change your factory like this -

app.factory('weatherService',['$resource', function($resource){
var factory={};
factory.getWeather = function(){
     return $resource("http://api.wunderground.com/api/9eb7777065b59c55/conditions/q/CA/:city.json", {city: '@id'});
 }
return factory;
}]);

You should change your controller like this -

 app.controller('weather', ['$scope', '$http','weatherService',   function($scope, $http, weatherService){
     $scope.weather = weatherService
     .getWeather()
     .get({city: 'San_Fransisco'}, function(){
         //other logic
     });
 }]);

$scope.weather has the json object returned from the server

Upvotes: 1

jegtugado
jegtugado

Reputation: 5141

Perhaps you can use JSON.parse to convert your JSON string to an object and go from there...

 $scope.weather = JSON.parse(weatherService.getWeather().get()); // JSON 
 $scope.weatherUrl = $scope.weather.url;

Upvotes: 0

Related Questions