Binding variables from Service/Factory to Controllers
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>
Deividi Cavarzan
Updated on April 07, 2020Comments
-
Deividi Cavarzan about 4 years
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?
-
sambomartin almost 10 yearsSo essentially, the factory is just a shared (singleton) container for data and functions on the data. You manually manage / sync the data in and out of the $scope?
-
user4815162342 almost 10 years@sambomartin right. Great article here
-
mtpultz over 9 yearsSo by passing the function as testFactory.getCount and not invoking it, and invoking it within the UI you have bound the services value. Whereas if you $scope.countFactory = testFactory.getCount() you would just invoke the function once when initialized and nothing is bound? So not updated later if value changes?
-
Aram about 9 years@sambomartin, factory is not singleton. If you want to have a singleton container use service instead. Service and Factory are basically the same in angular just with the difference that Service is singleton and Factory is not.
-
chipit24 almost 9 years@Aram No, a factory is a singleton too; all services in Angular are singletons. When you register a factory function on the module, it will create a service instance when called.
-
devonj about 8 yearsthought this was a good example of returning an object from the factory to the controller: stackoverflow.com/questions/22906196/…