AngularJS : The correct way of binding to a service properties

前端 未结 10 1827
天命终不由人
天命终不由人 2020-11-28 00:30

I’m looking for the best practice of how to bind to a service property in AngularJS.

I have worked through multiple examples to understand how to bind to properties

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 00:58

    Building on the examples above I thought I'd throw in a way of transparently binding a controller variable to a service variable.

    In the example below changes to the Controller $scope.count variable will automatically be reflected in the Service count variable.

    In production we're actually using the this binding to update an id on a service which then asynchronously fetches data and updates its service vars. Further binding that means that controllers automagically get updated when the service updates itself.

    The code below can be seen working at http://jsfiddle.net/xuUHS/163/

    View:

    This is my countService variable : {{count}}

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


    Service/Controller:

    var app = angular.module('myApp', []);
    
    app.service('testService', function(){
        var count = 10;
    
        function incrementCount() {
          count++;
          return count;
        };
    
        function getCount() { return count; }
    
        return {
            get count() { return count },
            set count(val) {
                count = val;
            },
            getCount: getCount,
            incrementCount: incrementCount
        }
    
    });
    
    function ServiceCtrl($scope, testService)
    {
    
        Object.defineProperty($scope, 'count', {
            get: function() { return testService.count; },
            set: function(val) { testService.count = val; },
        });
    
        $scope.clickC = function () {
           $scope.count++;
        };
        $scope.chkC = function () {
            alert($scope.count);
        };
    
        $scope.clickS = function () {
           ++testService.count;
        };
        $scope.chkS = function () {
            alert(testService.count);
        };
    
    }
    

提交回复
热议问题