0

Let's assume I have some service and some controller. What that service will return depends of what the controller will pass into it. But is it possible indeed? I suspect a service may look like this:

var app = angular.module('tApp',[])
.provider('getFileContents', function(param){
    this.paramId = param;
    this.$get = function(){
        var par = this.paramId;
        return{
            getContents:function(){
                return "paramId comes here: "+par;
            }
        }
    }
});

then I think my controller should look like this:

app.controller('test_controlController',
    function test_controlController($scope,getFileContents){
        $scope.contents = getFileContents.getContents('test_control');
        console.dir($scope.contents);
});

...but it doesn't work. It says:

Uncaught Error: Unknown provider: param from tApp 

So is it possible to make it working?

srgg6701
  • 1,878
  • 6
  • 23
  • 37

2 Answers2

2

You are adding a parameter to the service constructor instead to the service function. and you are using a provider instead of a service or factory, you can get some information about the difference between services/factories and providers here:

Angular Service VS Provider VS Factory

Back to your code, make to following changes:

Service:

app.service('FileService', function ()  {
    return {
        getFileContents : function (fileID) {
            //function logic goes here
            console.log(fileID);
        }
    }
});

Controller:

app.controller('TestController', function ($scope,getFileContents) {
    $scope.contents = getFileContents.getFileContents(123);
});
Community
  • 1
  • 1
Chancho
  • 1,930
  • 2
  • 15
  • 20
1

Add a parameter for your getContents method in your service

return{
            getContents:function(foo){
                return "paramId comes here: "+ foo;
            }
        }
smk
  • 5,340
  • 5
  • 27
  • 41