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

时间:2016-07-18 17:19:42

标签: javascript angularjs angularjs-ng-repeat ng-repeat

我正在尝试在将新项目推送到列表后使用ng-repeat更新视图,但是ng-repeat仍然保留旧引用。这是我的代码 (function(){     “使用严格”;

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>

仍然显示旧列表,我在另一篇文章中读到,这是因为引用而发生但我试图解决很多不同的方法而没有运气。

1 个答案:

答案 0 :(得分:0)

在您推送新消息的任何地方,请更改:

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 es以查找已更改的数据,其中一些数据库由ng-repeat等指令用于更新DOM。