Giordano
Giordano

Reputation: 5570

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

Upvotes: 3

Views: 14265

Answers (6)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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());
});

Upvotes: 2

Sunil Lama
Sunil Lama

Reputation: 4539

Yes, it is possible to share the scope variables between controllers through services and factory.But, the $scope variables are local to the controller itself and there is no way for the service to know about that particular variable.I prefer using factory, easy and smooth as butter. If you are using the service of factory in a separate file you need to include the file in index.html

 app.controller('Ctrl1', function ($scope,myService,$state) {
        $scope.variable1 = "One";
        myService.set($scope.variable1);
        $state.go('app.thepagewhereyouwanttoshare');//go to the page where you want to share that variable.
    });

 app.controller('Ctrl2', function ($scope, myService) {
   console.log("shared variable " + myService.get());
});
    .factory('myService', function() {
      function set(data) {
        products = data;
      }
      function get() {
        return products;
      }

      return {
        set: set,
        get: get
      }

    })

Upvotes: 5

Jonas
Jonas

Reputation: 2249

Update: Using $rootScope is considered bad practice.

What you need is the $rootScope. The $scope is just for one controller. Here is an example:

angular.module('myApp', [])
.run(function($rootScope) {
    $rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
  $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
})
.controller('myCtrl2', function($scope, $rootScope) {
    $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.changeRs = function() {
        $rootScope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
});

Upvotes: 0

Mark Santiago
Mark Santiago

Reputation: 463

First, your service should be like this:

app.service('share', function () {
    // this is a private variable
    var variable1;
    return {
        // this function get/sets the value of the private variable variable1
        variable1: function (newValue) {
            if(newValue) variable1 = newValue;
            return variable1;
        }
    };
});

To set the value of the shared variable pass the value to the function we created on the service

app.controller('Ctrl1', function ($scope, share) {
    $scope.variable1 = "One";
    // share the value of $scope.variable1
    share.variable1($scope.variable1);
});

To get the value of the shared variable also use the function in the service without passing a value

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

Upvotes: 0

martin
martin

Reputation: 96889

Best way is really using services. Services have only access to $rootScope, they don't have their own $scope.

However, you shouldn't use scopes for this task. Just make a service with some shared variable outside any scopes.

.service('share', function ($scope) {

    var variable = 42;

    return {
        getVariable: function () {
            return variable;
        }
    };
});

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

    // Watch for changes in the service property
    $scope.$watch(function() { return share.getVariable(); }, function(oldValue, newValue) {
        // whatever
    });
});

Upvotes: 0

suvroc
suvroc

Reputation: 3062

Your try with service it quite good, but you shouldn't try to use $scope in dependency injection into the service code. Service is meant to be a data provider to you, then if you want to share some data between 2 controllers, you should make place for this data in your service

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

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

This is the broader description of this solution: https://stackoverflow.com/a/21920241/4772988

Upvotes: 0

Related Questions