簡體   English   中英

將輸入推送到數組並清除輸入未按預期工作

[英]Push input to array and clear input not working as expected

我有一個從工廠獲取數據的控制器,如下所示:

.controller('ChatDetailCtrl', function($scope, $stateParams, Messages) {
  $scope.messages = Messages.get($stateParams.partnerId);
  $scope.send = function (input) {
    input.id = Math.random();
    input.sent = true;
    input.time = new Date();
    $scope.messages.data.push(input);
    console.log($scope.messages);
  }
})

我使用ng-repeat在模板上顯示消息。 然后,我有了一個使用ng-click運行send的輸入。 問題是,當您發送它時,它將其添加到數組中,但是,如果您繼續鍵入,它將更新發送的消息,而不是允許您發送新消息。

如何以一種允許我重復多次的方式將輸入傳遞給數組?

嘗試使用angular.copy,以便您不推送相同的引用,而是推送與輸入類似的全新對象

.controller('ChatDetailCtrl', function($scope, $stateParams, Messages) {
  $scope.messages = Messages.get($stateParams.partnerId);
  $scope.send = function (input) {
    input.id = Math.random();
    input.sent = true;
    input.time = new Date();
    $scope.messages.data.push(angular.copy(input));
    console.log($scope.messages);
  }
})

在沒有看到您的標記和/或input的結構的情況下,這可以解決問題:

JsBin: http ://jsbin.com/xevabevi/10/edit

就像Charminbear所說的那樣,在推送到message數組之后,您需要以某種方式清除輸入數據。

或者,您可以在推送中執行以下操作:

$scope.arr.push(angular.copy(input));

這樣,您就不會將輸入數據推送到數組,而會推送其副本。 但是,這不會清除您的輸入字段,因為原始input將保持不變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM