javascript - AngularJS using http.get with ng-model -
i trying create simple weather web application using angularjs. using weather api , want make input box page loads weather according city user inputs.
here code:
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 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 }}°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; }; });
i had working no input box , had "london" "$scope.location" inside http.get(). when use code , type london input box, not work.
thanks in advance!
first need wrap $http
in function
$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"; }); }
then use event ng-submit
call function
<form ng-submit="getdata()"> please enter location: <input type="text" ng-model="location"> <button>get data</button> </form>
Comments
Post a Comment