How do I retrieve the date from a dynamically generated text field within an ng-repeat loop and pass it

I have a specific issue with accessing the value of dynamically created input text in my web form. The problem arises when using ngRepeat to manage items, particularly with $scope.newValueItem being undefined. How can I retrieve the value from dynamically generated input fields?

HTML

<form role="form" name="itemsManagementRrnForm">
    <div class="panel panel-default">
        <div class="panel-body">
            <div class="row">
                <div class="col-md-6" data-ng-repeat="(formControllerKey,formControllerValue) in displayModel track by $index">
                    <div class="panel panel-default">
                        <div class="panel-heading">{{formControllerKey}}</div>
                        <div class="panel-body">
                            <div style="overflow-y: scroll; height:400px;">
                                <ul>
                                    <li data-ng-repeat="formControllerValue in formControllerValue track by $index" data-ng-hide="formControllerValue.deleted">
                                        <div id="showItem" data-ng-show="!displayModel[formControllerKey][$index].editingMode">
                                            <input class="" type="submit" value="Edit" data-ng-click="toggleEdit(formControllerKey,$index)">
                                            <input class="" type="submit" value="Delete" data-ng-click="deleteValue(formControllerKey,$index)">
                                            <label>{{formControllerValue.formControllerValueName}}</label>
                                        </div>
                                        <div id="editItem" data-ng-show="displayModel[formControllerKey][$index].editingMode">
                                            <input class="" type="submit" value="update" data-ng-click="updateValue(formControllerKey,$index)">
                                            <input class="" type="submit" value="Cancel" data-ng-click="cancel(formControllerKey,$index)">
                                            <input type="text" size="30" data-ng-model="formControllerValue.formControllerValueName" placeholder="add new here">
                                        </div>
                                    </li>
                                </ul>
                            </div>
                            <div>
                                <input class="" type="submit" value="add" data-ng-click="addValue(formControllerKey,formControllerValue[$index].formControllerID,$index)">
                                <input type="text" size="30" data-ng-model="newValueItem" placeholder="add new here">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

JS

 (function () {
    'use strict';

    var app = angular.module('athena');

    var ItemsManagementRrnFormController = function ($scope, $location, authService, userInfoService, itemsManagementRrnFormService) {

        var username = '';
        $scope.addValue = function (formControllerKey, parentId,index) {

            $scope.model = formValueModelTemplate();
            $scope.model.formControllerID = parentId;
            $scope.model.createdBy = username;
            $scope.model.CreatedOn = new Date();
            $scope.model.modifiedBy = username;
            $scope.model.modifiedOn = new Date();
            $scope.model.formControllerValueName = $scope.newValueItem;
            $scope.displayModel[formControllerKey].push($scope.model);
            itemsManagementRrnFormService.postValue($scope.model);
            $scope.newValueItem = '';

        };
    };

    app.controller('ItemsManagementRrnFormController', ['$scope', '$location', 'authService', 'userInfoService', 'itemsManagementRrnFormService', ItemsManagementRrnFormController]);

}());

Answer №1

You are facing a scoping challenge.

The issue lies in the fact that your controller has its own scope, and there is only one $scope.newValueItem within it.

When using ng-repeat, a new scope is created for each iteration, making your controller's $scope.newValueItem independent for each instance in the ng-repeat loop;

To address this, you have two options: either pass the newValueItem into the add method, or expand each display model to include a value for the input. This will allow you to reset each item individually when the "add" button is clicked, and prevent Angular from creating duplicate instances of newValueItem in each child scope created by ng-repeat.

$scope.displayModel = {
   controllerKey1: {
      data: [],
      newValueItem: ''
   }
}

I have provided a quick example on jsFiddle: http://jsfiddle.net/g9tm6y0c/5/

UPDATE: Here is another jsFiddle demonstrating the scoping issue. http://jsfiddle.net/9w0dy8ut/

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

Arranging items in ng-options through the use of orderBy

Here is the code I am struggling with: <select ng-model="i.br" ng-options="item.name as info[item.name] for item in e.br | orderBy:info[item.name]" class="combobox"> Unfortunately, the orderBy function is not sorting the options according to info[i ...

JavaScript code to record the time when a client exits my website by clicking the X button in the top right corner and save it in my database

I need to record in the database the times when users enter and exit my site. Saving the entry time is not an issue, nor is saving the exit time by clicking my "log off" button. However, what about when a client exits by clicking the X in the right corner ...

Trying to retrieve a value from a map in TypeScript and getting the error "map.get is not a function"

I am currently facing an issue with my map implementation where I have strings set as keys and values. However, when attempting to retrieve a value using a key, I encounter an error. Below is the code snippet that I am working with: let map:Map<string, ...

The alertify.alert function encounters issues when used within the response of a mithril m.request

I'm currently working on a project utilizing mithril.js and also integrating alertify.js. I am encountering an issue when trying to alert some data in the response. Strangely, it doesn't work as expected. However, if I use the same alert function ...

Display an image with only a portion visible, no canvas, no frame, and no need

My dilemma involves an img with a surrounding box div. http://jsfiddle.net/6d4yC/7/ 1) I am seeking to display only a portion of the image (250x150) without generating a white overlay when it is in its large size. Placing a #box1 div around the image has ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...

Error in Virtual Earth: The function is undefined

Currently, I am attempting to implement lazy loading for a Virtual Earth map within a JQuery UI tab. Concurrently, there is also a Google map in another tab. My goal is to synchronize the center locations of both maps whenever a user interacts with either ...

Ways to extract output from another file's standard output?

Take this scenario for instance, Consider having the following code snippet in a file labeled main.js: function main(){ console.log(5); } Now, imagine another file where you aim to extract the stdout from main.js. Presently, your code looks like t ...

I am looking to incorporate detailed explanations within my code utilizing jsdoc

Explaining the onChange function using jsDoc in my component repository. I want to ensure that users understand the parameters it accepts. However, I'm unsure if my explanation will be clear enough for others to grasp. This is my component /** * @ty ...

The Angular bootstrap datepicker does not correctly format the date value stored in the ng-model variable

I am currently utilizing a bootstrap date-picker in my Angular application. However, whenever I select a date from the date-picker, the underlying ng-model that I have bound gets updated. I would like that ng-model to be in the date format 'MM/dd/yyyy ...

Streaming videos using Flask with a custom template

After successfully implementing the DWA path planning algorithm in C with Python bindings, I have decided to create a web application demo. The concept involves a "robot" following the mouse using DWA, while allowing users to draw walls for objects. My ini ...

Creating a JSON object in AngularJS is a simple and straightforward process

Is it a good practice to create a JSON object in AngularJS this way? Or is there a better solution to achieve the desired format? Edit question: I am trying to create an object in JSON format as shown below. I have written the code but facing difficulty ...

Tips for triggering window load event on a particular page

I need to trigger the windows.load event on a specific page. Currently, I have set it up like this: $(window).load(function(){ if(document.URL == "/car-driving.html") { overlay.show(); overlay.appendTo(document.body); $('.popup' ...

Unable to toggle sidebar in Angular Material component

I'm trying to create a template similar to Youtube using angular material, but I've hit a roadblock with the sidebar navigation. Here are the requirements for the template: 1. The sidebar should be open by default (based on screen size) 2. When t ...

Utilize form controller to reference form controls that are dynamically named

Imagine a scenario like this (note that this example is artificially created): <form name="myForm"> <input name="{{'myInput'}}" ngModel="data.myInputModel"> </form> In my understanding, referencing it should be like: $scope ...

Navigating with Express while incorporating React

I am struggling to set up the routes for my web application using Express, as well as incorporating React for the front end. The issue lies in properly routing things when React components are involved. My index.html contains: <script> document.get ...

Using jQuery, what is the best way to conceal a Div while the scroll bar is in motion?

Is there a way to make the #menu fade when the scroll bar is in motion, creating a cleaner interface? I'm hoping to find code that will detect scroll bar movement, allowing the #menu to gradually fade out after 1 second of scrolling and come back aft ...

The functionality of Ajax is currently disabled on the latest mobile Chrome browsers

I have successfully created a modal form with dependent dropdown lists, and I am populating these lists using an ajax call. The functionality works smoothly on desktop browsers and most mobile browsers, but there seems to be an issue on certain newer versi ...

Error: The current element cannot be clicked. Please try again

I have been attempting to trigger a click event on another button within an onClick event function. An error occurred: Uncaught TypeError: this.clickBack.current.click is not a function The React version being used is 16.8.6 constructor(props) { s ...

Guide on enabling automatic rotation using Javascript

Recently, I came across a slider online that unfortunately did not have an autorotate feature. Despite my attempts to add an autorotate function using setTimeout and click functions, I was unsuccessful. This particular slider contains 4 buttons for each s ...