Binding variables from Service/Factory to Controllers

AngularjsAngularjs Directive

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

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>

Solution 2 - Angularjs

It's not good idea to bind any data from service,but if you need it anymore,I suggest you those following 2 ways.

  1. Get that data not inside your service.Get Data inside you controller and you will not have any problem to bind it.

  2. You can use AngularJs Events feature.You can even send data to through that event.

If you need more with examples here is the article which maybe can help you.

http://www.w3docs.com/snippets/angularjs/bind-value-between-service-and-controller-directive.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDeividi CavarzanView Question on Stackoverflow
Solution 1 - AngularjsjusioView Answer on Stackoverflow
Solution 2 - AngularjsHazarapet TunanyanView Answer on Stackoverflow