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?

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Guess I'm getting to spoiled with the two way data binding. Thx.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.