Unable to display information from a repeated `textarea` in ngRepeat

Check out my code on Plunker: https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L

I'm trying to log the content of each textarea when typing, using the printStuff() function:

$scope.printStuff = function(customize, item) {
    console.log(customize[item.index].data);
};

However, I encounter an error message once I start typing in a textarea:

angular.js:14290 TypeError: Cannot read property 'data' of undefined
    at b.$scope.printStuff (index.html:31)
    at fn (eval at compile (angular.js:15118), <anonymous>:4:299)
    at b.$eval (angular.js:17922)
    at angular.js:25653
    at Object.<anonymous> (angular.js:28429)
    at q (angular.js:325)
    at Object.$$writeModelToScope (angular.js:28427)
    at angular.js:28420
    at g (angular.js:28339)
    at f (angular.js:28322)

Any suggestions on how to resolve this issue?

AFTER FOLLOWING MannFromReno's ADVICE

The error still persists. Here is the updated Plunker link: https://plnkr.co/edit/WwC3kNiTQzaQfjp40h2a

Answer №1

Can you clarify where the index property comes from? You might consider using the $index variable provided by ng-repeat.

Please refer to the updated plunker: https://plnkr.co/edit/fHJlQPWiD872Fy9fXhMs

Is this the desired behavior?

Answer №2

To update the binding of your textarea, follow these steps:

<textarea rows="6" cols="60" placeholder="Enter data here." ng-model="customize[$index].details" ng-change="displayContent($index)"></textarea>

Ensure that your displayContent function is as shown below:

$scope.displayContent = function(index) {
  console.log($scope.customize[index].details);
};

A common mistake was trying to bind to the item.index property, which does not exist. Instead, use $index within a ng-repeat loop to get the current iteration index.

For a working example, check out this demo

Answer №3

Check out the code snippet below for a solution:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript">
var app=angular.module("myApp",[]);

app.controller("myCTRL",function($scope){
$scope.items=[{}];

$scope.customize=[{data: 'hi'}];

$scope.addChart=function(){
$scope.customize.push({
data: ''
});
};

$scope.removeChart=function(){
$scope.items.splice(-1,1);
};
$scope.removeWhichone = function(id, data){
  //$scope.customize.splice($scope.customize.indexOf(data), 1); 
  angular.forEach($scope.customize, function(value, key) {
            if (key === id){
                $scope.customize.splice(key, 1);
            }
        });
}

$scope.printStuff=function(customize,index){
//console.log(customize[index].data);
});
</script>;

<body ng-app="myApp" ng-controller="myCTRL">
<div>
<button ng-click="addChart()">Add</button>
<!--<button ng-click="removeChart()">Remove</button> -->
      
</div><br>
<div ng-repeat="item in customize">
<form novalidate>
<textarea rows="5" cols="50" placeholder="Paste data here." ng-model="customize[$index].data" ng-change="printStuff(customize,$index)"></textarea>
<button ng-click="removeWhichone($index, item)">Remove</button>
<br><br>
</form>

</div>
{{customize}}
</body>

Answer №4

Revise like this:

<div ng-repeat="item in items" ng-init="index = $index;">
    <form novalidate>
        <textarea rows="5" cols="50" placeholder="Paste data here." ng-model="customize[index].data" ng-change="printStuff(customize, selected.index)"></textarea>
        <br>
    </form>
</div>

The ng-model should refer to the 'data' property inside the customize object rather than the object itself as ngModel.

You can see a demonstration on Plunker: https://plnkr.co/edit/lqA5Fg8UAz81IM9v3Kts?p=preview

Answer №5

When passing the $index variable from the user interface to the printStuff function, remember to include it as a parameter.

<form novalidate>
     <textarea rows="5" cols="50" placeholder="Paste data here." ng-model="$scope.customize[$index]" ng-change="printStuff(customize,item,$index)"></textarea>
    <br>
</form>

$scope.printStuff = function(customize, item, index){
    console.log(customize[index].data);
};

https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L?p=preview

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

Tips for testing nested HTTP calls in unit tests

I am currently in the process of unit testing a function that looks like this: async fetchGreatHouseByName(name: string) { const [house] = await this.httpGetHouseByName(name); const currentLord = house.currentLord ? house.currentLord : '957'; ...

Display PickerIOS when a button is clicked in a React Native application

I am a beginner with the react framework and I'm trying to implement a PickerIOS component on button click. However, I'm having trouble understanding how to call other classes upon an event. I found this code snippet on the React Native site: v ...

Can user-generated code execute Javascript Promises in its entirety?

Can one fully implement the JavaScript Promise class using only userspace code, without relying on any support from native code (such as the internals of JavaScript) that would typically only be accessible to those working on a JavaScript engine like the V ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...

Idle Time in Nextjs - Making the Most of D

I've been experiencing a significant delay of around 6 seconds when refreshing my Next.js platform. As part of my debugging process to identify the root cause of this issue, I uncovered that approximately 5 seconds of this time is classified as idle. ...

I'm trying to set it up so that an image pops up when I hover over text. I've tried incorporating a few different JavaScripts, but I still can

I'm struggling to display an image on my website. I have the necessary code parts, but it's not working as expected. function showImage() { $('.img').addClass('display'); } function hideImage() { $('.img'). ...

jquery, slideToggle not behaving correctly on mouse hover

Whenever the mouse hovers over my div with the class .frame, I slideToggle a div with the class .content. And when the mouse leaves .frame, I toggle .content back again. Everything seems to be working fine except for two issues: the effect gets messed up i ...

Sending a collection of nested arrays to an MVC controller

Currently, I am utilizing spring MVC and have the requirement to transmit data to my controller on the backend server. @RequestMapping(value="/project/update") public @ResponseBody projectWebForm update(HttpServletRequest request, HttpServletRespo ...

In which specific location within the Bootstrap CSS files can the `footer` class be found?

Being new to coding, I've grasped HTML and CSS classes and am now delving into Bootstrap. Despite my efforts, I can't seem to locate the footer class in any of the Bootstrap CSS files like bootstrap.css. Similarly, I'm having trouble findi ...

Learn how to retrieve the value of an associated field at a specific index by utilizing a combo box in JavaScript when receiving a JSON response

Hey there, I'm currently working on a phone-gap app where I need to fetch data from a WCF service that returns JSON responses. Specifically, I want to display the DesignName in a combo box and pass the associated designId. Any thoughts on how I can ac ...

What occurs when the update function returned by React.useState() is invoked?

Just recently, I delved into the world of React hooks and decided to implement a small feature using them. The feature enables hidden texts to be displayed when users click on hyperlinks. Although I managed to make the code work, it appears that there are ...

Enhance an item by introducing additional properties derived from its current key-value pairs

I have a task of converting the following object: myObj = { "pageName": "home", "dataExtract": "data1|data2=value2|data3=value3|data4=value4a,value4b,value4c"} Into this format: myObjMod = { 'pageName': 'home', 'dataExtract&apos ...

What could be the reason for the absence of the back button?

Having trouble understanding why the back button isn't showing up when I navigate to an <ion-view> app root state template: <ion-side-menus> <ion-side-menu side="left"> <div class="list"> <!-- ... --> & ...

Does the webworker function as a multi-thread?

For example: worker.postMessage(data1); worker.postMessage(data2); If there are multiple issues to be dealt with inside the web worker, would worker.postMessage(data2) block before completing data1? ...

Durandal attempts to retrieve a view located within the viewmodel directory

Having an issue with durandal's compose binding as it is looking for views under app/viewmodels instead of app/views The ViewModel code: define(["fields/fieldClosures"], function (fields) { var ctor = function(opt) { this.value = opt.valu ...

Obtain a transformed mesh that has been displaced using a displacementMap within three.js

Seeking to extract and export the mesh affected by a displacementMap. The displacement of vertexes is determined by this line in the shader (taken from three.js/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl): transformed += normalize(obje ...

What is the best way to optimize angular code for production environments?

My development project, utilizing Node and Angular, is ready to go into production. How can I minify the Angular code for production? I am looking to minify or uglify the following controller. Whenever I try to minify the code online, the application stop ...

Guide to Embedding a SQL Table into an HTML Table

I need to set up a table within my current webpage to showcase a list of movies along with their genres. Welcome to my Movies page. The index.php file contains all the necessary database credentials and establishes the connection. <?php session_start( ...

position the input and span elements side by side

Need help aligning an input and a span element next to each other. The span is currently positioned below the input, but I want it to be on the right side of the input. I am trying to create a search bar using this input and span tag, so they need to be al ...

Encountered an issue while executing the next build process

Every time I run npm next build, it throws an error message. Despite my efforts to search for a solution online and installing the "extract-text-webpack-plugin," the issue persists. The error being thrown is as follows: > next build (node:8136) Depre ...