Krishna Srinivas Krishna Srinivas - 3 months ago 16
AngularJS Question

angular: Error: Unknown provider during module.config()

I get

Uncaught Error: Unknown provider: testProvider from myApp
in the below code:

test
is a custom provider.

angular.module('myApp', [])
.config(function (testProvider) {
testProvider.setPrefix("works: ");
});


Full code is here:

angular.module('myApp', [])
.config(function (testProvider) {
testProvider.setPrefix("works: ");
});


angular.module('myApp')
.provider ("test", function () {
var prefix;
this.setPrefix = function(p) {
prefix = p;
}

this.$get = function () {
return {
log: function(msg) {
console.log (prefix + msg);
}
}
}
});

angular.module('myApp')
.controller ("myCtrl", function($scope, test) {
$scope.$watch ('myModel', function (newval) {
test.log(newval);
})
});


Plunker link: http://plnkr.co/edit/zcIHRn?p=preview

Answer

A call to

module.provider("test", ...);

is really a call to

module.config(function($provide) {
  $provide.provider("test", ...);
});

(See my wiki article on dependency injection for more details.)

And since config blocks run in the order they were declared, you just need to move the declaration of your provider to above the point where it's used. You'll often see it written something like this:

angular.module('myApp', [])
  .provider ("test", function () {
    var prefix;
    this.setPrefix = function(p) {
      prefix = p;
    }

    this.$get = function () {
      return {
        log: function(msg) {
          console.log (prefix + msg);
        }
      }
    }
  })
  .config(function (testProvider) {
    testProvider.setPrefix("works: ");
  })
  .controller ("myCtrl", function($scope, test) {
    $scope.$watch ('myModel', function (newval) {
      test.log(newval);
    })
  });

An example: http://plnkr.co/edit/AxTnGv?p=preview

If you really want to keep the concerns separate, you can create a new module and set up a dependency:

angular.module('logging', [])
  .provider ("test", function () {
    var prefix;
    this.setPrefix = function(p) {
      prefix = p;
    }

    this.$get = function () {
      return {
        log: function(msg) {
          console.log (prefix + msg);
        }
      }
    }
  })

angular.module('myApp', ['logging'])
  .config(function (testProvider) {
    testProvider.setPrefix("works: ");
  })
  .controller ("myCtrl", function($scope, test) {
    $scope.$watch ('myModel', function (newval) {
      test.log(newval);
    })
  });

Example: http://plnkr.co/edit/PWtDFG?p=preview