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

The click function operates only once

Here are two simple JavaScript functions: CTCC.Transactions.PieceRecuClick = function (source) { $(".chk input[type='checkbox']").attr('checked', true); } CTCC.Transactions.PieceNonRecuClick = function (source) { $(".chk input ...

Using $regex in mongodb's pipeline operations allows for advanced string

I need to be able to use $regex in order to search for any words that contain a specific keyword provided by the user, but I'm experiencing issues. Here's what I have so far: aggregatePipeline.push({ $match: { name: { $reg ...

Adding elements to an array using JavaScript

What is the correct way to add new values to an array like this? json = {"awesome":"45.22","supercool":"9876"} I attempted json.push("amazingness":"45.22");, but unfortunately it was not successful. ...

What is the best way to utilize ng-if in the index.html page depending on the URL?

Is there a way to hide certain elements in the index page based on the URL of nested views? In my index.html file, I am looking to implement something like this: <top-bar ng-if="!home"></top-bar> <ui-view class="reveal-animation"> ...

Is there any npm module available that can generate user-friendly unique identifiers?

Struggling to come across a user-friendly and easily readable unique ID generator for storing orders in my backend system. I have considered using the timestamp method, but it seems too lengthy based on my research. ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

Triggering an action with JQuery when clicking on a button within an Angular

I need to open a new link whenever a column in my datatable is clicked. Below is the code for my datatable which fetches data through an ajax call- <table datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="featuretable row-border compact ...

Retrieving a Table Row from a TableView in Titanium Mobile

Does anyone know where the actual tableViewRows are stored within a TableView? When inspecting the TableView, I can see the headings for the Rows but not the Rows themselves. Can someone point me in the right direction to find where these Rows are contai ...

What is the process for building .ts components within a Vue application?

Looking to update an old project that currently uses the 'av-ts' plugin and vue-ts-loader to compile .ts files as Vue components. The project is running on Vue 2.4.2, but I want to upgrade it to version 2.6.14. However, since 'vue-ts-loader& ...

React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality. // src/componen ...

Incorporate React Components into a traditional HTML, CSS, and JavaScript project

Can I incorporate a React Native Component (https://www.npmjs.com/package/react-native-gifted-chat) into my vanilla JavaScript project? Is it feasible to embed a React Native component within a vanilla JavaScript project? If yes, then what is the process ...

How can you implement a resource response approach in Express.js using an API?

As a newcomer in my journey with expressjs, I'm currently exploring its functionalities. In my controller, I've structured the response as follows: .... res.json({ 'data': { 'user': { 'id': us ...

Issue with optimizing in Webpack 4

It's past 2am and I find myself going crazy trying to identify an error. The console keeps repeating the message: "Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead." I've attempted modifyi ...

React JS for loop not displaying any output

I am trying to create a component that loops from 0 to the value entered as a prop. if (props.number !== "" && props.toPow !== "") { for (let i = 0; i < props.toPow; i++) { return ( <div> & ...

Transform the Data into JSON format

I need assistance converting my data into the correct JSON format. The current structure of my data is as follows: [ "{ id:001, name:akhilesh, }", "{ id:002, name:Ram, }" ] My goal is to transform the above data into valid J ...

Accessing React Context globally using the useContext hook

I'm feeling a bit puzzled about how the useContext hook is intended to function in a "global" state context. Let's take a look at my App.js: import React from 'react'; import Login from './Components/auth/Login'; import &apos ...

Collaboratively utilizing resources among various NPM Workspaces

Currently, I am working on a React project using NPM Workspaces. I have created an 'assets' workspace within this project to store all images and assets that need to be accessed by other workspaces. The directory structure of the project is as fo ...

Create an AngularJS directive that dynamically adds another directive to the DOM when clicked

I am looking to implement an AngularJS directive that creates a button and upon clicking it, I aim to dynamically add another AngularJS directive (component) to the page. Can anyone guide me on how to achieve this functionality successfully? Here is my " ...

Field must have a base type specified to proceed

Currently, I am in the process of developing a discord.js bot. The structure I have set up involves a folder that contains all the commands, and when a command is called, index.js directs it to the appropriate file. However, when attempting to run the bot, ...

Utilizing Javascript to maintain an ongoing sum within a <span> tag

I'm working on a code snippet to create a running total feature. Essentially, every time a user clicks a button to add the subtotal to the total, I want it to keep accumulating in the running total. Currently, the setup involves a dropdown menu with t ...