Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding variables from Service/Factory to Controllers

I have a variable that will be used by one or more Controllers, changed by Services. In that case, I've built a service that keeps this variable in memory, and share between the controllers.

The problem is: Every time that the variable changes, the variables in the controllers aren't updated in real time.

I create this Fiddle to help. http://jsfiddle.net/ncyVK/

--- Note that the {{countService}} or {{countFactory}} is never updated when I increment the value of count.

How can I bind the Service/Factory variable to $scope.variable in the Controller? What I'm doing wrong?

like image 402
Deividi Cavarzan Avatar asked Apr 15 '13 19:04

Deividi Cavarzan


1 Answers

You can't bind variables. But you can bind variable accessors or objects which contain this variable. Here is fixed jsfiddle.

Basically you have to pass to the scope something, which can return/or holds current value. E.g.

Factory:

app.factory('testFactory', function(){     var countF = 1;     return {         getCount : function () {              return countF; //we need some way to access actual variable value         },         incrementCount:function(){            countF++;             return countF;         }     }                }); 

Controller:

function FactoryCtrl($scope, testService, testFactory) {     $scope.countFactory = testFactory.getCount; //passing getter to the view     $scope.clickF = function () {         $scope.countF = testFactory.incrementCount();     }; } 

View:

<div ng-controller="FactoryCtrl">      <!--  this is now updated, note how count factory is called -->     <p> This is my countFactory variable : {{countFactory()}}</p>      <p> This is my updated after click variable : {{countF}}</p>      <button ng-click="clickF()" >Factory ++ </button> </div> 
like image 130
jusio Avatar answered Sep 23 '22 06:09

jusio