-1

I am trying to share data between controllers in angularjs using a factory. I have followed other answers to similar questions but I can only get this to work 1st time round. I have an app with 3 states. 1 of the states is a simple calculator. I want the total in the calculator state to also be displayed in a different state. With the code below the total is always displayed as 0. So i think it works 1st time round but does not update when 'total' is changed. Anyone any suggestions??

html:

<div class="list card">
  <div class="item item-divider">Total</div>
  <div class="item item-body">
    <div ng-model="figure">
      <b>{{figure}}</b> calories consumed today
    </div>
  </div>
</div> 

'home' controller:

.controller('homeCtrl', function($scope, total) {

$scope.figure = total.get();

})

calculator controller:

.controller('calcCtrl', function($scope, total) {

$scope.result = 0;

$scope.reset = function() {
    $scope.result = 0;

};

$scope.add = function(i) {
    if(!i){

    }else {
        $scope.result = $scope.result + parseInt(i);
        total.set($scope.result);

    }
};

});

factory

.factory('total', function() {

var val = 0;

return {
get: function() {
    return val;
},
set: function(num) {
    val = parseInt(num);
    }
};  
})
daragh
  • 487
  • 9
  • 18
  • 2
    possible duplicate of [Angular: Share data between controllers](http://stackoverflow.com/questions/21919962/angular-share-data-between-controllers) – Julien Apr 30 '15 at 14:31
  • Yes, i studied the answers there and thought I have done everything as they did but I still cannot get the data shared. – daragh Apr 30 '15 at 14:32
  • 2
    You're binding to a primitive. See how he binds to an object in that answer? Return an object instead of a value from your service and bind to the `object.prop`. – Neil Smith Apr 30 '15 at 14:40
  • Thanks @NeilSmith. Got it working. I thought I had studied the previous answer! obviously not enough. – daragh Apr 30 '15 at 14:54

1 Answers1

2

It will work better if you use an object to store the value(s).

var data = {val : 0};
return {
  get: function() {
    return data;
  },
  set: function(num) {
    data.val = parseInt(num);
  }
};  

or you always call the get() function to get the latest value

.controller('homeCtrl', function($scope, total) {
   $scope.figure = total.get;
})

and in the HTML

<b>{{figure()}}</b>
Michael
  • 3,085
  • 1
  • 17
  • 15