Andre Fuentes
Andre Fuentes

Reputation: 98

how to pass a variable from controller scope to factory

So I want the user to be able to change the cityName used by this service:

app.factory("getWeatherJSON", ['$http', function ($http) {
    return $http.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=8c644b89f214d6bee6c2123faabfb05&units=metric`)
        .then(function (data) {
            return data;
        })
        .then(null, function (err) {
            return err;
        });
}]);

This is my controller (where the cityName comes from):

app.controller("mainController", ["$scope", "getWeatherJSON", function mainController($scope, getWeatherJSON) {
    $scope.cityName = "Rio de Janeiro";
    getWeatherJSON.then(function (data) {
        const weatherData = data.data;
        console.log(weatherData)
    })
}])

I tried to use $scope.cityName inside the service without success like this:

return $http.get(`https://api.openweathermap.org/data/2.5/weather?q=${$scope.cityName}&appid=8c644b89f214d6bee6c2123faabfb05&units=metric`)

Upvotes: 2

Views: 41

Answers (1)

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use below option
1. Wrap factory return in another function passing cityName
2. Use $scope.name value as parameter value i.e getWeatherJSON($scope.cityName)

Shortcut method to perform GET request.

Factory:
app.factory("getWeatherJSON", ['$http', function ($http) { return function(cityName){ return $http.get(https://api.openweathermap.org/data/2.5/weather? q=:cityName&appid=8c644b89f214d6bee6c2123faabfb05&units=metric)
} }]);

Controller:
app.controller("mainController", ["$scope", "getWeatherJSON", function mainController($scope, getWeatherJSON) { $scope.cityName = "Rio de Janeiro"; getWeatherJSON($scope.cityName).then(function (data) { const weatherData = data.data; console.log(weatherData) }) }])

Upvotes: 2

Related Questions