这是我第一次使用Angularjs $资源,我正在尝试对我的应用程序进行一些测试。我正在尝试访问其中一个属性而不是显示整个对象。如何访问data.image或data.url?
来自天气地下的json数据 {
"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"
}
天气工厂
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;
}]);
天气控制器
app.controller('weather', ['$scope', '$http','weatherService', function($scope, $http, weatherService){
$scope.weather = weatherService.getWeather().get();
}]);
答案 0 :(得分:1)
您对$资源的实施是错误的,改变您的工厂 -
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;
}]);
你应该改变你的控制器 -
app.controller('weather', ['$scope', '$http','weatherService', function($scope, $http, weatherService){
$scope.weather = weatherService
.getWeather()
.get({city: 'San_Fransisco'}, function(){
//other logic
});
}]);
$ scope.weather具有从服务器返回的json对象
答案 1 :(得分:0)
也许您可以使用JSON.parse将您的JSON字符串转换为对象并从那里开始......
$scope.weather = JSON.parse(weatherService.getWeather().get()); // JSON
$scope.weatherUrl = $scope.weather.url;