16

I am trying to create a factory in AngularJS based on this article. But I am getting an error saying "dataFactory" is undefined in my controller. My code looks like this:

MyApp.factory('dataFactory', ['$http', function($http)
    {
        var urlBase='/someurl/roles/';
        var dataFactory={};

        dataFactory.getRoles=function()
        {
            return $http.get(urlBase+'getlist');
        };

        dataFactory.addRole=function(roleName, roleCss)
        {
            return $http.get(urlBase+'add&name='+roleName+'&css='+roleCss);
        };

        dataFactory.updateRole=function(role)
        {
          return $http.get(urlBase+edit&id='+role.id+'&name='+role.name+'&css='+role.css');
        };

        dataFactory.deleteRole=function(role)
        {
            return $http.get(urlBase+'remove&id='+role.id);
        };

        return dataFactory;
    }]);

MyApp.controller('RoleCtrl',['$scope','$http','dataFactory', function($scope,$http,$rootScope,dataFactory) {
     dataFactory.getRoles().then(function(res){
        $scope.roles = res.data.result;   
      });
 }]);

What am I doing wrong?

1 Answer 1

27

You're missing the string version of '$rootScope'

So instead of

MyApp.controller('RoleCtrl',['$scope','$http','dataFactory', function($scope,$http,$rootScope,dataFactory) {

use (note the addition of '$rootScope'):

MyApp.controller('RoleCtrl',['$scope','$http','$rootScope','dataFactory', function($scope,$http,$rootScope,dataFactory) {

dataFactory was going into $rootscope since you had a misalignment of parameters. And then there was nothing to send in to dataFactory. Thus your error.

Sign up to request clarification or add additional context in comments.

1 Comment

You saved my day. Sometimes my mouse just deletes random bits of code and I wouldn't even notice it. Cheers mate!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.