Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

angularjs - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...