With the weather service and route defined on the Node.js server side, you can implement a controller that accesses the route to get weather data. Listing 29.10 implements weatherController
in the AngularJS application Module
object. The scope contains a list of cities and the location or city name used when getting weather data. Also, a locationIn
value is defined to provide a model for a text input to add new city names.
The getWeather()
function makes an $http GET
request, passing the city parameter from $scope.location
, and sets the $scope.weather
value that will be bound to the view.
The addCity()
function uses locationIn
to add new cities to the cities array. If a city already exists, then it is not added. The location is set to the new city, and getWeather()
retrieves the weather data.
001 var app = angular.module('richApp', []);
. . .
050 app.controller('weatherController', function($scope, $http) {
051 $scope.cities = ['London', 'Paris', 'New York',
052 'Rome', 'Los Angeles'];
053 $scope.location = $scope.cities[0];
054 $scope.locationIn = '';
055 $scope.getWeather = function(){
056 $http({url: '/weather', method: "GET",
057 params:{city:$scope.location}})
058 .success(function(data, status, headers, config) {
059 $scope.weather = data;
060 })
061 .error(function(data, status, headers, config) {
062 $scope.weather = data;
063 });
064 };
065 $scope.addCity = function(){
066 if ($scope.cities.indexOf($scope.locationIn) != 0){
067 $scope.cities.push($scope.locationIn);
068 }
069 $scope.location = $scope.locationIn;
070 $scope.getWeather();
071 };
072 $scope.setLocation = function(city){
073 $scope.location = city;
074 $scope.getWeather();
075 };
076 $scope.getWeather('London'),
077 });
18.223.213.238