0

Here's a service:

myApp.factory('myService', function() {
    var test = 5;

    return{
      setTestVal: function(val){
        test = val;
      },
      getTestVal: function(){
        return test;      
      }
    }    
});

This is my controllers. One get the value and one sets it

function MyCtrl($scope, myService) {
    $scope.test = myService.getTestVal();
}

function SetCtrl($scope, myService){
    $scope.newTestVal = '';
    $scope.setTestVal = function(val){
      myService.setTestVal(val)
    }
}

But the view is not updated when I set the value.

Fiddle: http://jsfiddle.net/HB7LU/7036/

Is this the wrong approach to setting and getting values?

Joe
  • 4,274
  • 32
  • 95
  • 175

2 Answers2

1

No, this approach is perfectly fine, however the view has no idea when a new value is set, you have to setup a $watch on the shared property:

$scope.$watch(function() {
    return myService.getTestVal();
}, function(value) {
    $scope.test = value;
});

Fiddle: http://jsfiddle.net/HB7LU/7041/

tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

You even could do it without $watch, check fiddle i modified from yours :

var myApp = angular.module('myApp',[]);
myApp.factory('myService', function() {
    var test = 5;
    var obj = {
        test : 5
    }

    return{
      setTestVal: function(val){
        test = val;
        obj.test = val;
      },
      getTestVal: function(){
        return test;      
      },
      data : obj
    }


});

function MyCtrl($scope, myService) {
    $scope.test = myService.getTestVal();
    $scope.data = myService.data;
}

function SetCtrl($scope, myService){
    $scope.newTestVal = '';
    $scope.setTestVal = function(val){
      myService.setTestVal(val)
    }
}

http://jsfiddle.net/no9rv2nb/