Binding variables from Service/Factory to Controllers

前端 未结 2 1065
抹茶落季
抹茶落季 2020-11-29 18:26

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 betwee

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 19:06

    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:

    This is my countFactory variable : {{countFactory()}}

    This is my updated after click variable : {{countF}}

提交回复
热议问题