1

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;
    })
  }
})
heatherblairs
  • 151
  • 2
  • 12
  • This error means angular can't find the controller. For starters check that your `index.html` includes the script that contains the controller Also check that you used the exact controller name in your routes config and/or `ng-controller` definition. – Ladmerc Mar 09 '17 at 15:13

1 Answers1

1

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.

Community
  • 1
  • 1
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • FYI, both `(function(){ })()` and `(function(){ }())` work equally. There was no need to edit that. – Harris Mar 10 '17 at 16:23
  • 1
    @HarrisWeinstein, yes! I noticed that just after I edited it :) :) I'm so used to use this style (_Douglas Crockford's style_) that I came to believe the other way was incorrect. Thanks for your clarification. [Here](http://stackoverflow.com/questions/8774425/vs-in-javascript-closures) there are other options too. Cheers! – lealceldeiro Mar 10 '17 at 16:41
  • Neat, I didn't know about those other ways. – Harris Mar 10 '17 at 17:08