当数据在另一个URL上更新时,AngularJS是否可以在一个URL上触发$watch

Can AngularJS trigger $watch on one URL when data is updated on another URL

本文关键字:URL 一个 watch 是否 更新 另一个 数据 AngularJS      更新时间:2024-01-30

我想知道当数据库中的更改不是由当前页面上的用户操作引起时,我是否可以触发数据库中更改的$watch

例如,控制器:

.MesgCtrl(...)
$scope.data = {'name': 'Tim', 'visits': 0};
$scope.$watch('data', function(newValue, oldValue) {
  console.log("$watch triggered");
  });

例如,在模板上.html我有:

<ul ng-repeat="d in data">
  <li>{{d}}</li>
</ul>

不同的 REST 端点 URL 获取访问的 POST 请求,并在访问发生时在数据库中更新它们。 我想在模板上更新访问计数.html以便用户查看它们何时在数据库中更新。但是,到目前为止,我只能在调用$resource.save()更新来自同一 AngularJS 控制器 URL 而不是来自不同 URL 的访问$watch工作。

如果您需要两种通信方式,例如当其他人访问页面时在客户端上更新,您可以使用像 socket.io http://socket.io/这样的图书馆来访问每个连接的套接字(。

您还可以添加一个计时器来请求服务器,例如每 30 秒请求一次,并获取访问计数器的更新(为此使用 $interval(。

如果只想在经过一定时间后请求一次,请使用 $timeout

$interval致力于计划数据刷新,并将更改拉取到 Web 浏览器客户端。 这是我使用的代码:

conciergeControllers.controller('MessageCtrl',
    function MessageCtrl($scope, $stateParams, $interval, Message, GuestMessages) {
        $scope.messages = {};
        $scope.getGuest = function(GuestMessages, $stateParams, $scope) {
            GuestMessages.get({
                id: $stateParams.guestId
            }, function(response) {
                $scope.guest = response;
                $scope.to = response.phone_number;
                $scope.messages = response.messages;
                // test
                console.log('Guest:', $scope.guest);
            });
        }
        // populate initial context without a delay
        $scope.getGuest(GuestMessages, $stateParams, $scope);
        $interval(function(){ $scope.getGuest(GuestMessages, $stateParams, $scope); }, 5000);
    }
);