Search code examples
javascriptangularjsangularjs-scopeangularjs-service

AngularJs: pass $scope variable with service


I have two controllers and in one of them I declared a $scope variable that I would like visible in the second controller.

First controller

app.controller('Ctrl1', function ($scope) {
    $scope.variable1 = "One";
});

Second Controller

app.controller('Ctrl2', function ($scope, share) {
   console.log("shared variable " + share.getVariable());
});

I researched the best Angular approach and I found that is the use of service. So I added a service for Ctrl1

Service

.service('share', function ($scope) {
    return {
        getVariable: function () {
            return $scope.variable1;
        }
    };
});

This code return this error:

Unknown provider: $scopeProvider <- $scope <- share

So my question is: is possible share $scope variable between controllers? Is not the best Angular solution or i'm missing something?

Sorry for my trivial question but I'm an Angular beginner.

Thanks in advance

Regards


Solution

  • You cannot inject $scope dependency in service factory function.

    Basically shareable service should maintain shareable data in some object.

    Service

    .service('share', function () {
        var self = this;
        //private shared variable
        var sharedVariables = { };
        self.getSharedVariables = getSharedVariables;
        self.setVariable = setVariable;
    
        //function declarations
        function getSharedVariables() {
            return sharedVariables;
        }
        function setVariable() {
            sharedVariables[paramName] = value;
        }
    });
    

    Controller

    app.controller('Ctrl1', function ($scope, share) {
        $scope.variable1 = "One";
        share.setVariable('variable1', $scope.variable1); //setting value in service variable
    });
    
    app.controller('Ctrl2', function ($scope, share) {
        console.log("shared variable " + share.getSharedVariables());
    });