How to dynamically set a value in an AngularJS text field

Clicking "edit" will show the form in HTML below:

<div ng-repeat="item in items">
    <input type="text" placeholder="{{item.questionPlaceholder}}" ng-model="form.g1tags[item.tags_index]" required>
    <input ng-class="{'blockInput': !item.inlineChecked}" type="text" placeholder="enter text..." ng-model="form.g1tags_desc[item.tags_index]"  required>
   <input type="hidden" name="Group1" value="1">
</div>                         
<button class="addfields" ng-click="addG1Choice()">Add fields</button>

Check out the function in my Angular controller:

  $scope.edit = function(id){
    dataFactory.httpRequest('items/'+id+'/edit').then(function(data) {
        //console.log(data);
        $scope.form = data;


        for(var key in data) {
            var tags = data[key];
        }
        for(var i = 0; i < tags.length; i++){
            tag = tags[i];
            //console.log(tag['name']);
            $scope.tags_index += 1;
                    $scope.items.push({ 
                        tags_index: $scope.tags_index,
                        tag_name: tag['name'],
                        inlineChecked: false,
                        question: "",
                        questionPlaceholder: tag['name'],
                        text: ""
                    });
            $scope.form.g1tags = 'aaaaaaaaaaaaaaaaaaaaaaaaab';
            console.log ($scope.form.g1tags);

        }

    });
  }

The textfield seems to only display the first character of 'aaaaaaaaaaaaaaaaaaaaaaaaab'. Can anyone help with what could be causing this issue?

Answer №1

The reason for the issue is that you are only accessing the first element within ng-repeat. To fix this, you should remove [item.tags_index] from ng-model.

<input type="text" placeholder="{{item.questionPlaceholder}}" ng-model="form.g1tags" required>

Answer №2

Within your controller, you have assigned a single string value to g1tags:

$scope.form.g1tags = 'aaaaaaaaaaaaaaaaaaaaaaaaab';

However, within your view, you are trying to access it as if it is a collection:

form.g1tags[item.tags_index]

This approach will not work correctly. If you require g1tags to hold multiple values, consider creating an array instead:

$scope.form.g1tags = [];

//Within your for loop:
$scope.form.g1tags.push('aaaaaaaaaaaaaaaaaaaaaaaaab');

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

A step-by-step guide on fetching multiple iframe contents simultaneously with Selenium in Java

Today, I am facing an interesting challenge. I need to extract the page source of a webpage that includes an iframe. Surprisingly, when using the PhantomJSDriver with the code snippet below, I am only able to retrieve either the page content or the iframe ...

Toggle Jquery feature will dynamically add the "required" attribute to the input field when the specified div is visible, and it will automatically remove the attribute when the div

I am new to using jQuery and I am facing an issue with my code. I want to make a checkbox act as a toggle with jQuery. When the checkbox is clicked and the toggle displays the div, I want to add the required attribute to the checkbox input. Similarly, when ...

The table element fails to display in IE11 due to a rendering issue, displaying the error message: "Render error - TypeError: Object does not support the property or method 'entries'"

As someone new to web app development, I am currently working on a project that involves using Vue cli and antd components, with the additional challenge of ensuring compatibility with IE11. However, I have encountered an issue where IE11 does not render ...

Retrieving Information from JSON File Using a Variable (JavaScript/Discord.js)

While I was coding my Discord bot, I encountered an unexpected issue. Normally, after linking a JSON file, you can access data by using jsonFile.path to retrieve specific information. However, I faced a challenge where I needed to replace the path with a ...

Is it possible to use AngularJS promise scheduling with `async`/`await` syntax?

When working with AngularJS services, TypeScript often recommends that I switch my code to use async/await functions. While I understand that using the await keyword is compatible with third-party promises because it essentially translates to calling then ...

Troubles encountered when cascading val(), text(), and data()

Here is my JavaScript/jQuery code: $select.append($("<option />") .val(this.id) .text(this.text) .data('name', this.name) .data('isstorage', this.isstorage)); Although it successfully assigns values to t ...

Focus on an empty <input> tag with just the type attribute

In what way can React Testing Library be utilized to isolate a blank <input> element that solely possesses a type attribute? For instance, consider an input field that will eventually have attributes added dynamically, much like the surrounding labe ...

Socket IO: Error - The call stack has exceeded the maximum size limit

Whenever a client connects to my node.js server, it crashes with a 'RangeError: Maximum call stack size exceeded' error. I suspect there's a recursive problem somewhere in my code that I can't seem to find. This is the code on my serve ...

Creating evenly spaced PHP-generated divs without utilizing flexbox

My goal is to display images randomly from my image file using PHP, which is working fine. However, I am facing an issue with spacing the images evenly to fill the width of my site. This is how it currently appears: https://i.stack.imgur.com/AzKTK.png I ...

creating a JSON object in PHP that can be easily parsed by JavaScript

In my project, I have an extensive list of items, each item further divided into four sub-items. While it's convenient for me to organize this data in nested arrays using PHP, I encounter issues when trying to transfer them as a JSON object to the cli ...

Ways to update the content of a NodeList

When I execute this code in the console: document.querySelectorAll("a.pointer[title='Average']") It fetches a collection of Averages, each with displayed text on the page: <a class="pointer" title="Average" onclick="showScoretab(this)"> ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

What is the best way to incorporate Form Projection into Angular?

I have been attempting to incorporate form projection in Angular, inspired by Kara Erickson's presentation at Angular Connect in 2017, but I am encountering difficulties and errors along the way. view talk here The code provided in the slides is inco ...

retrieve the date value of Focus+Context by using the Brushing Chart

Currently, I am engaged in analyzing the sentiment of tweets on Twitter. The analysis will produce an overall area graph that allows me to choose a specific date range and extract all or some of the tweets falling within that range. In order to create a t ...

a method for inserting a space after a certain character, with the exception of when that character is located at the start or end of a line

I've created a regular expression that can modify various patterns like: anything1 * anything2* anything3 anything1* anything2 * anything3 anything1 * anything2 * anything3 anything1*anything2 *anything3 anything1 * anything2 *anything3 anything1*any ...

Implementing Checkbox Functionality within a Dropdown Menu using AngularJS or JavaScript

I am interested in finding a multi-select checkbox solution similar to the one demonstrated here: Instead of using jQuery, I would prefer options in AngularJS or pure JavaScript. Does such a solution already exist in these frameworks, or is there guidance ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

What is the best way to adjust the size of a button using CSS within a ReactJS

I am facing an issue where I need to create a button with a specific width, but the template I'm using already has predefined styles for buttons. When I try to customize the button's style, nothing seems to change. Below is the code snippet: Her ...

Utilizing Angular: Importing Scripts in index.html and Implementing Them in Components

Currently, I am attempting to integrate the Spotify SDK into an Angular application. While I have successfully imported the script from the CDN in index.html, I am encountering difficulties in utilizing it at the component level. It seems like there may be ...

What is the method to determine the overall size of a webpage using the Google PageSpeed API?

"analytics": { "cssResponseBytes": "333 kB", "htmlResponseBytes": "269 kB", "imageResponseBytes": "3.35 MB", "javascriptResponseBytes": "2.29 MB", "numberCssResources": 2, "numberHosts": 80, "numberJsResources": 72, "numberR ...