Shi*_*man 8 javascript url json angularjs
我正在研究Angular的一些大型简单天气应用程序,因为练习原因而且我被卡住了..
我有一个像这样的角度json feed:
app.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=Amsterdam,NL&lang=NL_nl&units=metric')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
Run Code Online (Sandbox Code Playgroud)
并将feed加载到index.html.它的全部工作和我现在的魔杖是索引上的输入表单,它改变了js/services/forcast.js上网址的阿姆斯特丹部分,其中上面的代码是另一个城市,所以人们可以看到他们的城市天气.
请参阅此处的演示:http://dev.bigstoef.nl/workspace/shiva/weer/index.html
我已经尝试了所有关于现在的可选选项,而且我还有3天了,这是不行的.这里有什么正确的方法?
首先,创建一个“可配置”服务:
app.factory('forecast', ['$http', function($http) {
var city;
var cities = {
amsterdam: 'Amsterdam,NL',
paris: 'Paris,FR'
};
var api_base_url = 'http://api.openweathermap.org/data/2.5/weather';
var other_params = 'lang=NL_nl&units=metric';
return {
setCity: function(cityName){
city = cityName ;
console.log(city);
},
getWeather: function(cityName){
console.log(city);
if(cityName) this.setCity(cityName);
if (!city) throw new Error('City is not defined');
return $http.get(getURI());
}
}
function getURI(){
return api_base_url + '?' + cities[city] + '&' + other_params;
}
}]);
Run Code Online (Sandbox Code Playgroud)
然后您可以创建一个如下所示的控制器:
app.controller('forecastCtrl', ['$scope', 'forecast',function($scope,forecast){
$scope.city = 'amsterdam' ;
$scope.$watch('city',function(){
console.log($scope.city);
forecast.setCity($scope.city);
});
$scope.getWeather = function(){
console.log('get weather');
forecast.getWeather()
.success(function(data){
console.log('success',data);
$scope.weatherData = data;
}).error(function(err){
console.log('error',err);
$scope.weatherError = err;
});
};
}]);
Run Code Online (Sandbox Code Playgroud)
实现模板如下
<link rel="stylesheet" href="style.css" />
Run Code Online (Sandbox Code Playgroud)
<div data-ng-controller="forecastCtrl">
<form>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'amsterdam'">Amsterdam
</label>
<br/>
<label>
<input type="radio" name="city" data-ng-model="city" data-ng-value="'paris'">Paris
</label>
<br/>
<button data-ng-click="getWeather()">Get Weather</button>
</form>
<p class="weather-data">
{{weatherData}}
</p>
<p class="weather-error">
{{weatherError}}
</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看代码:http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8 ?p=preview