0

I have a controller which fetches data from a factory, as follows:

.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);
  }
})

I use an ng-repeat to display the messages on the template. I then have an input which uses ng-click to run send. The problem is, when you send it then its added to the array, however if you carry on typing then it updates the sent message, rather than allowing you to send a new one.

How can I pass the input to the array, in a way which allows me to repeat it many times?

3
  • how about you add input = {} after you pushed it? Commented Jul 27, 2014 at 11:48
  • That doesn't do anything at all. Commented Jul 27, 2014 at 11:50
  • Maybe also post the template to make more clear what it is about. The Problem is that by pushing input into the Array, you still keep a reference inside your model ($scope), you dont refresh it. Commented Jul 27, 2014 at 11:55

2 Answers 2

1

try using angular.copy so that you are not pushing the same reference but an entirely new object similar to input

.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);
  }
})
Sign up to request clarification or add additional context in comments.

Comments

0

Without having seen your markup and/or the structure of input, this here does the trick:

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

Like Charminbear said, you need to clear the input data some way, after pushing to the messages array.

Alternatively, you could do the following in the push:

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

That way you wouldn't push the input data to the array, rather you would push a copy of it. This wouldn't clear your input fields however, as the original input would stay intact.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.