Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.