AngularJS 未使用 SignalR 更新 UI

AngularJS Not Updating UI With SignalR

因此,当我将 angularjs 代码放在 signalR 函数中时,它不会更新 UI。我什至使用 $scope.$apply() 强制消化。

这是我的代码:

var notificationHub = $.connection.progressNotificationHub;
notificationHub.client.displayAdminNotification = function (currentProgress, totalProgress, msg, finish) {
    $scope.$apply(function () {
        if ($scope.adminNotification == null)
            $scope.adminNotification = {};

        $scope.adminNotification.currentProgress = currentProgress;
        $scope.adminNotification.totalProgress = totalProgress;
        $scope.adminNotification.msg = msg;
        $scope.adminNotification.percentage = totalProgress == 0 ? 0 : (currentProgress / totalProgress) * 100;
        $scope.adminNotification.finish = finish;

        if (finish) {
            $scope.adminNotification = null;
        }
    })
};

$.connection.hub.start().done(function () {
});

这是我的 UI:

<!-- Notification -->
<div class="admin-notification-container" ng-show="adminNotification != null && showAdminNotification">
    <div class="dark-overlay" style="opacity:0.9"></div>
    <div class="admin-notification-content">
        <div class="admin-notification-progress">
            <p>Progress: {{adminNotification.currentProgress}} of {{adminNotification.totalProgress}}</p>
            <div class="admin-notification-progress-bar-container">
                <div class="admin-notification-progress-bar progress-bar progress-bar-striped progress-bar-animated" style="width:{{adminNotification.percentage}}%">{{adminNotification.percentage}}%</div>
            </div>
            <p class="admin-notification-msg">{{adminNotification.msg}}</p>
        </div>
    </div>
    <div class="hide-admin-notification" ng-click="toggleAdminNotification()">-</div>
</div>

<div ng-show="adminNotification != null && !showAdminNotification" class="hide-admin-notification-hide" ng-click="toggleAdminNotification()">^</div>

更新

经过进一步调查。当我的 webapi 服务器向 UI 发送消息时,displayAdminNotification 函数中使用的“$scope”与声明的 $scope 不同。它声明了一个新的 $scope 并使用它。

为什么会这样?

好的,问题是我的控制器被触发了两次。这是因为我有嵌套控制器。

<div ng-app="app" ng-controller="ctrl">
    ......
        <div ng-app="anotherApp" ng-controller="controller"></div>
</div>

我使用扩展另一个控制器的控制器。像这样:

app.controller('ctrl', adminController);

adminController.$inject = ["$scope", "$controller", "$http", '$sce'];

function adminController ($scope, $controller, $http, $sce)
{
    angular.extend(this, $controller('controller', { $scope: $scope }));
    .....

遇到这种问题的,请检查一下你的控制器结构。