Storing the input into an array and resetting the input is not functioning as intended

A unique situation arises with the controller in which data is fetched from a factory:

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

An NG-repeat is utilized to showcase the messages on the template. Additionally, there is an input that triggers send using NG-click. The issue lies when you send a message, it gets added to the array. However, if you continue typing, it updates the sent message rather than allowing you to send a new one.

The challenge here is how to pass the input to the array in a manner that allows repetition multiple times?

Answer №1

Consider utilizing the angular.copy function to clone objects instead of pushing the same reference in order to maintain separate instances of input data.

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

Answer №2

Without having a glimpse at the structure of your markup and/or input, here's a solution that might work for you:

Check out this JsBin example for reference: http://jsbin.com/xevabevi/10/edit

As mentioned by Charminbear, make sure to clear the input data after pushing it to the messages array.

Alternatively, you can modify the push method like so:

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

This way, instead of pushing the original input data to the array, you'll be pushing a copy of it. This won't erase the content from your input fields because the original input will remain unchanged.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to eliminate the default background color applied to the body automatically?

I'm currently developing a Covid-19 tracking web application and I am using chartJS to showcase data from an API. In my CSS, I have assigned a background color to all elements with an asterisk (*), but for some reason there are empty spaces around the ...

Choose a list and convert it into an associated array

There is a select element containing options and corresponding values: <select id="sid"> <option value="sValue1">sText1</option> ... </select> To generate an associative array for all these pairs, the following ...

Unlocking Global Opportunities with Stencil for Internationalization

Hi there, I've been attempting to implement Internationalization in my stencil project but unfortunately, it's not working as expected. I'm not sure what's causing the issue, and all I'm seeing is a 404 error. I followed these arti ...

Sliding down dropdown menu with JQuery activation on click action

This is the code I have for opening a dropdown menu $smallScreenMenu when $iconMenu1 is clicked Javascript code: const $iconMenu1 = $('#iconMenu1') const $smallScreenMenu = $('#smallScreenMenu') $($iconMenu1.on('click', ()=& ...

Removing white spaces within a string in the C programming language

I'm currently working on a task to eliminate any blank spaces from a user-input string. I already have code in place that calculates the number of vowels and reverses the string. The part where I need assistance is with //spaces. What I've attemp ...

Dealing with various menu states using Material-UI Menu component: Tips and Tricks

I've encountered an issue with my dynamically generated dropdowns and accordions that appear at the client-side render (based on validated user purchases from the database). The error seems to stem from my menu anchor element not being able to pinpoi ...

Persist in the face of a mishap in javascript

Two scripts are present on the page. If the first script encounters an error, the second script will not function properly as a result. Is there a way to make the second script ignore any errors from the first one and still work? Please note that I am str ...

What is the best way to retrieve state within a property of a React class component?

I have encountered an issue with a React Class Component where I am trying to separate a part of the rendered JSX but unable to access the Component's state within the separated JSX as a property of the class. The scenario is quite similar to the fol ...

Javascript detecting key press event only firing once when a key is continuously held down

I have implemented the code below to redirect to a specific page when the w, s, a, d keys are pressed. <script> document.addEventListener('keydown', function(e){ e = e || window.event; key = e.keyCode || e.charCode; var keys = { 87: &ap ...

Can a JavaScript function be sent through a REST API using Node.js and Express?

I have a unique scenario where I need to send a custom JavaScript function as a response to a GET request made to an API endpoint. Currently, I am using Node.js with Express for my server implementation, but I am open to exploring other frameworks. When a ...

The integration of the Kik API with AngularJS and JSON is not functioning properly

My struggle with integrating angularjs code with the kik api continues: var myApp = angular.module('myApp', []); myApp.controller('MainCtrl', function($scope) { $scope.go = function() { kik.send({ title ...

What is the most efficient way to add a new element at the beginning of a jsonb array in PostgreSQL 12?

Example: drop table a; create table a( value jsonb); insert into a values ('{"items":[0,1,2]}'::jsonb); select value->'items' from a; I am familiar with appending to an array. For instance: select jsonb_build_object(' ...

PHP for extracting an inventory of products

I am encountering an issue with retrieving a list of items from a MySQL database and displaying them as options in a select element on a webpage. The specific code snippet causing the problem is outlined below. Initially, I am attempting to fetch a JSON o ...

Is there a way to determine if an iframe has finished expanding?

I have a contenteditable iframe that can be resized so that not all of its contents are visible. What is the best way to determine if this iframe is fully expanded or not? ...

Combine results from two sets of data into an array by utilizing the _.each() method

What I'm aiming for: I aim to make a call to an API and within that API, I want to achieve the following: Locate Bills Retrieve all transactions associated with each bill (using billId) Present the values in a JSON ARRAY Here is an example represe ...

Is it possible to create dynamic animations with SVG files?

I am currently in the process of coding my website, and I came up with an exciting idea to animate my navigation bar within an SVG container. With its naturally wavy design, I aim to achieve a sweeping wave effect similar to the intro animation on Discord. ...

Problem with the "md-open-on-focus" behavior in the Angular-Material's "md-datepicker" directive

When testing the functionality of the fiddle, an inconsistency issue was observed with multiple openings of the md-datepicker while using md-open-on-focus. The problem arises after the first successful opening and closing - subsequent attempts to open it ...

Retrieve all Tableau workbooks stored on the server

I am currently working with Tableau Server and have multiple workbooks published on it. My goal is to create a dropdown list that displays all the workbook names along with their corresponding URLs. This way, when a user selects a value from the dropdown, ...

Using AngularJS to connect a REST search endpoint to $resource mapping

The ng-resource module in AngularJS provides a default set of resource actions which include 'get', 'save', 'query', 'remove', and 'delete'. { 'get': {method:'GET'}, ...

By checking the active box and completing the fields, the button will be activated

I'm currently working on a form that requires all fields to be filled out and the acceptance checkbox to be checked before the Submit button becomes active. If any entry or the checkbox is subsequently removed, the button should become inactive again. ...