Search code examples
angularjsangularjs-controllerangularjs-factory

AngularJS Error, "Cannot read property of unknown"


I am trying to create a factory to retrieve weather data for a simple web page I am creating but, I am getting stuck when trying to call the function in the factory. I have fallowed Dan Wahlin's course on Udemy but I just cant figure out why I am getting the error. It definitely seems like I am doing something wrong but I can't figure it out. Here is code

HTML

<!DOCTYPE html>

<div ng-controller="WeatherController" style="position:absolute; top:0px; ">
    {{weather.weather.main}}<br>
    <img src='http://openweathermap.org/img/w/10d.png' height="100px" width="100px">
</div>

<div style="background-color:white; position: absolute; bottom:0px;">
    <canvas id="canvas" width="400" height="400">
    </canvas>
</div>

<script src="script/angular.min.js"></script>
<script src="app/app.js"></script>
<script src="app/services/WeatherFactory.js"></script>
<script src="app/controllers/WeatherController.js"></script>
<script src="script/clock.js"></script>

app.js

(function () {
angular.module('displayApp', []);

}());

WeatherController.js

(function () {

var WeatherController = function ($scope, $log, $http, weatherFactory) {
    $scope.weather = "";

    function init() {            
        weatherFactory.getWeather() //******This line stops with error*****
            .then(function (response) {
                $scope.weather = response.data;
            }, function (data, status, headers, config) {
                $log.log(data.error + ' ' + status);
            });

        // $scope.weather = "Get the weather?"
    }

    init();

};

WeatherController.$inject = ['$scope', 'weatherFactory'];

angular.module('displayApp').controller('WeatherController', WeatherController);

}());

WeatherFactory.js

(function () {
var weatherFactory = function ($http) {

    var factory = {};

    factory.getWeather = function () {
        //return $http.get('api.openweathermap.org/data/2.5/weather?q=Rancho Santa Margarita&appid=60f84f7ee9256ef5057de8b616105ab9');
        return "Get the weather";
    };

    return factory;
};

weatherFactory.$inject = ["$http"];

angular.module('displayApp').factory('weatherFactory', weatherFactory);

}());

Specific error is Cannot read property 'getWeather' of undefined at init (WeatherController.js:17)

What am I missing, or what am I doing wrong?

Any and all help is appreciated. Thanks.


Solution

  • You are missing a few injections. You currently have:

    WeatherController.$inject = ['$scope', 'weatherFactory'];
    

    And your arguments are $scope, $log, $http, weatherFactory. Just add the missing injections:

    WeatherController.$inject = ['$scope', '$log', '$http', 'weatherFactory'];