0

Why angular says me that setData is not a function?

angular.module('mdl').factory('DataService', ['$http', '$cookieStore', '$rootScope',
    function ($http, $cookieStore, $rootScope) {
        return {
            setData: function (data) {
                $rootScope.data = data;
            },
        };
    }
]);

Here is my controller which calls setData.

angular.module('mdl').controller('DataCtrl', ['$scope', '$http', '$location', '$rootScope', 'DataService',
function($scope, $http, $location, DataService) {

    $scope.getData = function (id) {
        $http.post('/rest/data/get', id)
            .success(function (data, status, headers, config) {
                DataService.setData(data);
                $location.path('/main');
            })
            .error(function (data, status, headers, config) {

            });
    };
}

]);

3
  • can you see the code where you call your setData ? Commented Jun 2, 2015 at 11:56
  • in controller use DataService.setData or your DataService object name Commented Jun 2, 2015 at 12:00
  • @MathieuBertin added controller code. Commented Jun 2, 2015 at 12:05

3 Answers 3

1

There is a problem on dependencies injection, you are declaring 6 items and in your function you have 5 items. And the missing is DataService.

['$scope', '$http', '$location', '$rootScope', 'DataService',
function($scope, $http, $location, $rootScope /*Missing*/, DataService) {
…
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you're declaring a function in service you should pass a this reference to function. You could do it like too

angular.module('mdl').factory('DataService', ['$http', '$cookieStore', '$rootScope',
    function ($http, $cookieStore, $rootScope) {

            this.setData: function (data) {
                return data;
            }

    }
]);

and in controller make this factory as a dependency and call factory's function like

$scope.data = DataService.setData();

You should not use $rootScope. You should use above call instead

1 Comment

But this for service, and I am using factory. I need to use $rootScope.
1

Replace DataService.setData(data); with LoginService.setData(data); in your controller, as you have renamed the factory when passed in as a parameter.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.