8

I'm working on some mega simple weather app in Angular for practice reasons and i'm stuck..

i have a angular json feed like this:

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; 
        }); 
}]);

and it loads the feed in to the index.html. its all working and what i wand now is a input form on index that changes the Amsterdam part of the url on js/services/forcast.js where the above code is to another city so people can see their city weather.

See the demo here: http://dev.bigstoef.nl/workspace/shiva/weer/index.html

Ive tryd about all posable options about now and i'm 3 days further and its a no go. What is there correct way here?

2
  • What is the controller code? Commented May 26, 2015 at 7:13
  • app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) { forecast.success(function(data) { $scope.weer = data; }); }]); Commented May 26, 2015 at 7:15

3 Answers 3

2

First, create a "configurable" service :

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;
    }
}]);

Then you can create a controller like the following:

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; 
    });    
}; 
}]);

To implement a template as the following

<link rel="stylesheet" href="style.css" />

<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>

You can view the code working here : http://plnkr.co/edit/rN14M8GGX62J8JDUIOl8?p=preview

Sign up to request clarification or add additional context in comments.

7 Comments

It seems you missed to include your ForecastCtrl in your index.html or you mispelled it (upper case ?). In my example code I used lower case forecastCtl. In the template and in the js. But in your index.html, you used uppercase <script src="js/controllers/ForecastCrtl.js"></script>. Replace it by <script src="js/controllers/forecastCrtl.js"></script> to get working
i see. thats kinda dumb of me.. yet i changed it all and still a no go... what am i doing wrong here....
Ok there is syntax error in the controller. See Edit CTRL in my post.
You just removed the whole CTRL ... just replace the first $scope.getWeather function by the new one
|
1

You can return a function in your factory. Define your forcast as

app.factory('forecast', ['$http', function($http) { 
 return {
     query: function(city) {
         return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&lang=NL_nl&units=metric') 
        .success(function(data) { 
          return data; 
        }) 
        .error(function(err) { 
          return err; 
        });
     }
 };

}]);

Then in your controller

forecast.query('Amsterdam,NL').success(function(data) {
  $scope.weer = data;
});

Comments

1

Change service code to have a dedicated method which you can call multiple times with different parameters (cities):

app.factory('forecast', ['$http', function($http) {
    return {
        load: function(location) {
            return $http.get('http://api.openweathermap.org/data/2.5/weather?q=' + location + '&lang=NL_nl&units=metric')
            .success(function(data) {
                return data;
            })
            .error(function(err) {
                return err;
            });
        }
    }
}]);

Then in controller you would be able to load forecat for other locations when you need:

forecast.load('Amsterdam,NL').then(function(data) {
    $scope. weer = data;
});

Demo: http://plnkr.co/edit/GCx35VxRoko314jJ3M7r?p=preview

3 Comments

ok i get this code! sorry for being a MEGA noob. but how do i change the "location" now trough a input form?
It depends on your application. In my demo I provided simple input field to enter location. It can be dropdown, or anything else. Check the demo.
ive tryd but i cant seems to get it in to my code.... when i do angular stops working...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.