I'm trying to load some JSON and store it using $rootScope so that it persists between controllers. When I run my app I get the following error:
TypeError: Cannot call method 'get' of undefined
The get method was working perfectly until I tried to introduce $rootScope... any ideas?
My service looks like this:
1 /**
2 * Service to get the quiz data from a JSON source
3 */
4 app.factory('quizService', ['$rootScope', function ($scope, $rootScope, $http) {
5 var promise;
6 var service = {
7 getQuiz: function($scope, $http) {
8 if ( !promise ) {
9 promise = $http.get('QuizFileName.quiz').then(function (response) {
10 return response.data;
11 });
12 }
13 return promise;
14 }
15 };
16 return service;
17 }]);
My controller looks like this:
7 // Get Quiz data from service
8 quizService.getQuiz().then(function(data) {
9 $scope.quiz = data;
10
11 // Redirect to scores if already completed this
12 if($scope.quiz.complete === true) {
13 $location.path('scores');
14 }
15 });
You are using the 'array pattern' in defining your factory. You should have a string for each of the services you use in your function, but you only have one.
That is, what you do is
app.factory('quizService', ['$rootScope', function ($scope, $rootScope, $http) {
//insert code
}]);
but what you should do is
app.factory('quizService', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {
//insert code
}]);
AngularJS will map the functions named with the strings to the parameters. Try that and see if it fixes your issue.
EDIT: Ah,the answer from Reboog711 makes more sense in solving the issue, I somehow missed the latter part of the code. But I'm leaving this answer in since you should also fix the factory definition.