gpt4 book ai didi

javascript - AngularJS 使用 http.get 和 ng-model

转载 作者:行者123 更新时间:2023-11-30 16:17:44 24 4
gpt4 key购买 nike

我正在尝试使用 angularJS 创建一个简单的天气 Web 应用程序。我正在使用天气 API,我想制作一个输入框,以便页面根据用户输入的城市加载天气。

这是我的代码:

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="./node_modules/angular/angular.js"></script>
<script src="./myApp3.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>

<body>
<h1>Weather Center</h1>
<div ng-app="myApp" ng-controller="myCtrl">
<form>
Please enter your location: <input type="text" ng-model="location">
</form>
<p id="field">
Location: <span id="result">{{ myData.data.name }}, {{ myData.data.sys.country }}</span>
</p>
<p id="field">
Current Conditions: <span id="result">{{ myData.data.weather[0].description }}</span>
</p>
<p id="field">
Temperature: <span id="result">{{ myData.data.main.temp | kelvinToFahrenheit | number: 0 }}&deg;F</span>
</p>
<p id="field">
Pressure: <span id="result">{{ myData.data.main.pressure }} mb</span>
</p>
<p id="field">
Wind Speed: <span id="result">{{ myData.data.wind.speed }} mph</span>
</p>
</div>

</body>
</html>

JS:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://api.openweathermap.org/data/2.5/weather?q=" + $scope.location + ",uk&appid=44db6a862fba0b067b1930da0d769e98")
.then(function(response) {
$scope.myData = response;
}, function(response) {
$scope.myData = "Something went wrong";
});
});

app.filter('kelvinToFahrenheit', function() {
return function(kelvin) {
return (parseFloat(kelvin) - 273.15) * 1.80 + 32.00;
};
});

我在没有输入框的情况下工作,我只有“伦敦”,其中“$scope.location”位于 http.get() 内。但是当我使用此代码并在输入框中键入 London 时,它不起作用。

提前致谢!

最佳答案

首先你需要将 $http 包装在一个函数中

$scope.getData = function(){
$http.get("http://api.openweathermap.org/data/2.5/weather?q=" + $scope.location + ",uk&appid=44db6a862fba0b067b1930da0d769e98")
.then(function(response) {
$scope.myData = response;
}, function(response) {
$scope.myData = "Something went wrong";
});
}

然后使用像ng-submit这样的事件来调用这个函数

<form ng-submit="getData()">
Please enter your location: <input type="text" ng-model="location">
<button>Get Data</button>
</form>

关于javascript - AngularJS 使用 http.get 和 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35236819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com