Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...