0

I want automatically refresh $scope.variable in both controllers to new value if data.variable in SharedFactory was changed:

.controller('FirstController', function($scope, SharedFactory) {
  $scope.variable = SharedFactory.getVal();
})

.controller('SecondController', function($scope, SharedFactory) {
  $scope.variable = SharedFactory.getVal();
  SharedFactory.setVal("test string 2");
})

.factory("SharedFactory", function () {
    var data = {                // all variables by default
        variable : 'test string'
    };
    return {
        getVal: function () {
            return data.variable
        },
        setVal: function (i) {
            data.variable = i;
        }
    }
});

http://plnkr.co/edit/b1RNcl6Pz2iuRr2t2Q9x?p=preview

So at this example correct result must be "test string 2" in both controllers. How to do that?

Paul Serikov
  • 2,550
  • 2
  • 21
  • 36
  • use $rootScope. You can find some examples following; http://stackoverflow.com/questions/18880737/how-do-i-use-rootscope-in-angular-to-store-variables – İsmail Şener Dec 13 '15 at 22:56

2 Answers2

0

Because you are using primitive variable instead of using object so once you set it you actually lose your reference to original object, so instead of returning data object value (which is primitive) you can return all data object...

getVal: function () {
    return data;
}

Here is update plunker...

Siyual
  • 16,415
  • 8
  • 44
  • 58
Poyraz Yilmaz
  • 5,847
  • 1
  • 26
  • 28
0

Easiest (and possibly more efficient) would be to have a reference to SharedFactory.data directly in your controllers - rather than to SharedFactory.data.variable. That way, when the value of data.variable changes it would change in all controllers as you reference the data-variable rather than the specific value. Using primitives is generally not reccomended.

Another solution would be to use $scope.$watch in your controllers, and just watch for changes on the value and update the local-variable when it changes.

Etse
  • 1,235
  • 1
  • 15
  • 28