推送新项目时 ng-repeat 不更新

ng-repeat not updating when pushing new item

我尝试在将新项目推送到列表后使用 ng-repeat 更新视图,但是 ng-repeat 仍然保留旧引用。这是我的代码 (功能 () { "use strict";

angular.module('messages', [])

.component('messages', {
    template: '<ng-outlet></ng-outlet>',
    $routeConfig: [
      { path: '/', name: 'MessageList', component: 'messageList', useAsDefault: true },
      { path: '/:id', name: 'MessageDetail', component: 'messageDetail' },
    ]
})

.component('messageList', {
    templateUrl: '/angular/spa/profile/components/messages/template/message-listing.template.html',
    controllerAs: "model",
    controller: ["$http", messageListController],
})

.component('messageDetail', {
    templateUrl: '/angular/spa/profile/components/messages/template/message-detail.template.html',
    controllerAs: "model",
    bindings: { $router: '<' },
    controller: ["$http", messageDetailController],
})

.component('messageBubble', {
    templateUrl: '/angular/spa/profile/components/messages/template/message-bubble.template.html',
    controllerAs: "model",
    controller: ["$http", messageBubbleController],
    bindings: {
        message: '<',
        user: '<'
    },
});

function messageBubbleController($http) {
    var model = this;
    model.$onInit = function () {
        model.currentUserId = $("#loggedInUserIdSignalR").val();
    };
}

function messageDetailController($http) {
    var model = this;
    model.item = null;
    model.user = null;
    model.message = null;
    model.loading = false;
    model.chatHub = $.connection.chatHub;
    model.$onInit = function () {
        model.loading = true;
    };
    model.sendMessage = function () {
        if (model.message.length > 0) {
            console.log(model.messages.length);
            model.chatHub.server.send(model.message, model.user.SubjectId, model.item.ItemId);
        }
    };
    model.chatHub.client.broadcast = function (message, date, recipientId, itemId, senderId, senderNickName, senderPicture) {
        $scope.$apply(function () {
            model.messages.push({
                ConnectionId: "",
                DateSent: "/Date(1468852585430)/",
                Message: message,
                Sender: senderId,
            });
        });
        console.log(model.messages.length);
        console.log('New incoming message: ' + name + " ->" + message)
    };

    this.$routerOnActivate = function (next) {
        var id = next.params.id;
        fetchConversationMessages($http, id).then(function (response) {
            model.loading = false;
            model.uid = response.uid;
            model.item = response.conversation;
            model.user = response.conversation.User;
            model.messages = response.conversation.messages;
        });
    };


    function fetchConversationMessages($http, id) {
        return $http.get("/profile/messages-data/" + id)
                    .then(function (response) {
                        console.log(response);
                        return response.data;
                    });
    }
}

function messageListController($http) {
    var model = this;
    model.conversations = []
    model.loading = false;
    model.$onInit = function () {
        model.loading = true;
        fetchConversations($http).then(function (conversations) {
            model.loading = false;
            model.conversations = conversations.results;
            console.log(model.conversations);
        });
    };

    model.$routerOnActivate = function (next) {
        console.log('messages list comp activated');
    }
    function fetchConversations($http) {
        return $http.get("/profile/conversationsData")
                    .then(function (response) {
                        return response.data;
                    });
    }
}

})();

在此代码块中

model.chatHub.client.broadcast = function (message,date,recipientId,itemId,senderId,senderNickName,senderPicture) {
            model.messages.push({
                ConnectionId: "",
                DateSent: "/Date(1468852585430)/",
                Message: message,
                Sender: senderId,
            });

            console.log(model.messages.length);
            console.log('New incoming message: ' + name + " ->" + message)
        };

是我获取新消息并将其推送到消息列表的地方,控制台日志显示更新后的列表,但是我的模板上有这个

<div class="chat-room">
        <pre>{{model.messages.length}}</pre>
        <message-bubble ng-repeat="msg in model.messages" message="msg" user="model.user"></message-bubble>
    </div>

这行代码

    <pre>{{model.messages.length}}</pre>

仍然显示旧列表,我在另一个 post 中读到这是由于引用而发生的,但我尝试了很多不同的方法但没有运气。

在你推送新消息的任何地方,改变:

model.chatHub.client.broadcast = function(...) {
            model.messages.push({
                ConnectionId: "",
                DateSent: "/Date(1468852585430)/",
                Message: message,
                Sender: senderId,
            });
        };

进入:

model.chatHub.client.broadcast = function(...) {
       $scope.$apply(function() {
            model.messages.push({
                ConnectionId: "",
                DateSent: "/Date(1468852585430)/",
                Message: message,
                Sender: senderId,
            });
        });
    };

另一个解决方案是为您的通信库找到 angularjs 包装器。

$scope.$apply 所做的基本上是告诉 AngularJS 您的应用程序使用的数据已更改并且需要 运行 再次摘要循环。正如您可能知道的那样,摘要循环会检查哪些数据发生了变化,运行 的所有 $watch 都是发生变化的数据,其中一些被 ng-repeat 等指令用于更新 DOM。