Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AngularJS Services and Dependencies Services: Requiring factories

Israel Bautista
Israel Bautista
2,391 Points

not sure why is not working after adding the dependency injection

I added the dependency injection to the controller but is not working. Cryptic error

app.js
angular.module('treehouseCourse', [])
  .factory('Course', function() {
    return {
      title: "Intro to Angular"
    }
  });

angular.module('treehouseCourse', [])
.controller('MyCourseCtrl',['Course', function('Course'){
  console.log(Course);
}]);
index.html
<!DOCTYPE html>
<html ng-app="treehouseCourse">
  <head>
    <title>Angular.js</title>
    <script src="js/angular.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MyCourseCtrl">
  </body>
</html>

2 Answers

Here is the code that worked for me.

angular.module('treehouseCourse', [])
  .factory('Course', function() {
    return {
      title: "Intro to Angular"
    }
  });

angular.module('treehouseCourse')
  .controller('MyCourseCtrl', ['$scope', 'Course', function($scope, Course) {
    console.log(Course);
  }]);

That worked? Shouldn't $course be Course?

Yes, this code successfully passes the challenge. I used Angular Dependency Injection reference docs to help.

someModule.controller('MyController', ['$scope', 'dep1', 'dep2', function($scope, dep1, dep2) {
  ...
  $scope.aMethod = function() {
    ...
  }
  ...
}]);

I understand your question now after seeing this post. I don't really know why I chose to name the variable $course. Updated answer to use Course instead.

I had a problem with understanding the angular syntax for a long time too, but I found a tutorial that cleared up DI syntax for me.

The reason why your original code function('Course')... did not work is because the word "Course" is supposed to be a parameter in the form of a variable. When you put quotes around it, you turned it into a string.

Your console.log(Course); statement therefore used an undefined "Course" variable.