Search code examples
javascriptangularjsangularjs-controllerangularjs-factory

AngularJS controller is not a function, got undefined (data from factory)


I'm refactoring an old AngularJS project so it's less dumb and bad, separating controllers and exporting data with a factory rather than having all the data inside of one giant controller. I can't get very far, unfortunately, because my main controller isn't working. I've searched SO extensively and none of the issues I've seen matched mine. I also ran it by a senior dev and he couldn't find the issue. Any help is much appreciated. The app did work before my refactoring efforts.

My index.html:

<!DOCTYPE html>
<html ng-app="campSpots">
<head>
<meta charset="utf-8">
<title>Camp Spots</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body ng-controller="mainCtrl">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" src="components/main.ctrl.js"></script>
</body>
</html>

My factory:

(function(){
"use strict";
  angular
   .module("campSpots")
   .factory("postFactory", function($http){
    function getPosts(){
    return $http.get('data/posts.json');
  };
  return {
    getPosts: getPosts
  };
 })
})

And my controller, main.ctrl.js:

(function(){
"use strict";
angular
   .module("campSpots")
      .controller("mainCtrl", mainCtrl);

      mainCtrl.$inject = ['$scope', '$http', 'postFactory'];

      function mainCtrl($scope, $http, postFactory){
    postFactory.getPosts().then(function(posts){
      $scope.posts = posts.data;
    })
  }
})

Solution

  • You neglected to invoke the function in your IIFE for both the controller and factory.

    They should go like this:

    (function(){
        ///code
    }());
    

    That last () is missing in your code, so it's not actually running the code blocks.