AngularJs绑定服务函数多次执行

AngularJs绑定服务函数多次执行,angularjs,factory,execution,Angularjs,Factory,Execution,我有以下代码示例: angular.module('test', ['ngRoute', 'ngAnimate']) .config(function($routeProvider) { $routeProvider .when('/', { templateUrl: 'test.template.html', controller: 'ctrlA', controllerAs: 'ctrlA'

我有以下代码示例:

angular.module('test', ['ngRoute', 'ngAnimate'])
.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'test.template.html',
            controller: 'ctrlA',
            controllerAs: 'ctrlA'
        })
        .when('/page', {
            templateUrl: 'page.template.html',
            controller: 'ctrlB',
            controllerAs: 'ctrlB'
        });
})
.controller('ctrlA', function(testfactory) {
    this.value = "a";
    this.fnc = testfactory.getAmount;

})
.controller('ctrlB', function(testfactory) {
    this.value = "b";

    this.inc = function() {
        testfactory.incAmount();
    };

})
.factory('testfactory', function(){

    var amount = 0;

    return {

        incAmount: function() {
            amount++;
        },

        getAmount: function() {
            console.log("getAmount");
            return amount;
        }

    };
})
.run();
如果我将路由从root更改为/page,然后再更改为back,则getAmount函数将执行多次。我的主要目标是,如果金额由其他控制器增加,则自动从服务中获取金额值。如何防止函数的多次执行

ctrlA的模板如下所示

{{ctrlA.fnc()}}

这可以通过向对象传递引用来实现:

// testFactory

var data = {
    amount: 0
}

// ctrl, inject service, ...

this.data = factory.data

// template 

{{ctrl.data.amount}}

我写了一篇关于此()的博客文章,您将在服务和多个控制器之间获得自动同步的数据。

不要忘记投票正确的答案,谢谢:)