繁体   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