AngularJS 从服务到控制器的通信 event/change

AngularJS communicating event/change from service to controller

我正在尝试在两个控制器之间进行通信。我知道这可以通过引发事件然后使用 $rootScope.$broadcast 来完成,但不建议用于大型应用程序。我看过很多博文推荐使用服务进行通信,但都未能成功实施。我的实际代码更复杂,但这里是要点:

HTML:

<body ng-app="app">
    <div ng-controller="MainCtrl">
        <span>Source: {{count}}</span>
        <button ng-click="updateCount()">Increase Count</button>
    </div>
    <div ng-controller="ListCtrl">
        Destination: {{updatedCount}}
    </div>
</body>

JS:

(function () {

    var app = angular.module("app", []);

    app.factory("ShareDataSvc", function ($log) {

        var currentCount = 0;

        var set = function (val) {
            $log.info('Setting service value to: ' + currentCount);
            currentCount = val;
        }

        var get = function () {
            return currentCount;
        }

        return {
            set: set,
            get: get
        }
    });

    app.controller("MainCtrl", ['$scope', 'ShareDataSvc', function ($scope, ShareDataSvc) {
        $scope.count = ShareDataSvc.get();
        $scope.updateCount = function () {
            $scope.count = $scope.count + 1;
            ShareDataSvc.set($scope.count);
        }
    }]);

    app.controller("ListCtrl", ["$scope", "ShareDataSvc", function ($scope, ShareDataSvc) {
        $scope.updatedCount = ShareDataSvc.get();

        // trigger alert if count updated
        $scope.triggerAlert = function () {
            alert('Count updated!');
        }
    }]);
}());

我想了解为什么 Angular 没有更新目标中的计数,即使它是数据绑定的。据我了解,当在 SharedDataSvc 中更新计数时,将重新计算 updatedCount 属性。 我在这里做错了什么?最终结果是在每次计数更新时触发警报。

你运行进入了旧的按值复制问题。当你做

$scope.updatedCount = ShareDataSvc.get();

更新后的计数 属性 被设置为从您的 get 函数返回的值,因此您的服务中跟踪的值不会在未来发生变化。你有两种选择来解决这个问题。一种是为您的每个控制器添加一个手表,以监控服务中的值。不理想。第二个是让服务中的对象 属性 跟踪值并将该对象绑定到您的范围。类似的东西(注意我只展示了有趣的部分):

app.factory("ShareDataSvc", function ($log) {

    var set = function (val) {
        $log.info('Setting service value to: ' + currentCount);
        this.data.count = val;
    }

    return {
        data: {count: 0}
        set: set
    }
});

app.controller("MainCtrl", ['$scope', 'ShareDataSvc', function ($scope, ShareDataSvc) {
    $scope.data = ShareDataSvc.data;
    $scope.updateCount = function () {
        ShareDataSve.data.count++; // and increment function in the service would be better
    }
}]);

app.controller("ListCtrl", ["$scope", "ShareDataSvc", function ($scope, ShareDataSvc) {
    $scope.data = ShareDataSvc.data;

}]);

然后在你的HTML

<body ng-app="app">
    <div ng-controller="MainCtrl">
        <span>Source: {{data.count}}</span>
        <button ng-click="updateCount()">Increase Count</button>
    </div>
    <div ng-controller="ListCtrl">
        Destination: {{data.count}}
    </div>
</body>