Binding variables from Service/Factory to Controllers

前端 未结 2 1044
抹茶落季
抹茶落季 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:

    <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>
    
    0 讨论(0)
  • 2020-11-29 19:11

    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

    0 讨论(0)
提交回复
热议问题