Tips for preserving input field data in an AngularJS scope variable

I am having trouble storing textbox values in my 'Values' variable. When I enter values in the textboxes, it seems to be getting the hard-coded values instead. Can someone please help me with this AngularJS issue as I am new to it? Here is the code snippet:

$scope.form = {
        site_name: 'Site name',
        street_address: 'Street address',
        city: 'City',
        state: 'State',
        country: 'Country',
        zip_code: 'Zip Code',
        phone_number: 'Phone Number'
    };

    $scope.addRow = function() {
        $scope.i++;
        $scope.array = [];
        for(var i = 0; i < $scope.i; i++) {
            $scope.array.push(i);
        }
    }

    var checkprofile = $scope.Profile.id;
    $(".alert").hide();

    $scope.updateProfile = function () {
        console.log('updateProfile');
        console.log($scope.form);
        $scope.Profile.addresses.push($scope.form);
        
        $scope.tempObject = {
            full_name: $scope.Profile.full_name,
            mobile_number: $scope.Profile.mobile_number,
            company_name: $scope.Profile.company_name,
            designation: $scope.Profile.designation,
            addresses: $scope.Profile.addresses,
            payment_info: $scope.Profile.payment_info
        };

        $http.put(properties.customerupdate_path + "/" + checkprofile, $scope.tempObject).success(function (response) {
            // window.location.href = '/customerprofile';
        });
    }

When I click a button after entering values in the textboxes, below code does not retrieve data from the textboxes but returns the previous hardcoded values:

$scope.updateProfile = function () { 
        console.log('updateProfile'); 
        console.log($scope.Values); 
    }

//result --> [Object {site_name="Site name", street_address="Street address", city="City", more...}]

}

HTML:

<tr ng-repeat="lines in array">
        <td><input type="text" class="form-control" id="inputDefault" ng-model='Values.site_name' name='site_name'></td>
        <td><input type="text" class="form-control" id="inputDefault" ng-model='Values.street_address' name='street_address'></td>
        <td><input type="text" class="form-control" id="inputDefault" ng-model='Values.city' name='city'></td>
        <td><input type="text" class="form-control" id="inputDefault" ng-model='Values.state' name='state'></td>
        <td><input type="text" class="form-control" id="inputDefault" ng-model='Values.country' name='country'></td>
        <td><input type="text" class="form-control" id="inputDefault" ng-model='Values.zip_code' name='zip_code'></td>
        <td><input type="text" class="form-control" id="inputDefault" ng-model='Values.phone_number' name='phone_number'></td>
    </tr>

Update Profile

https://i.sstatic.net/45jMp.jpg

Answer №1

$scope.info = {
    company_name: 'Company name',
    address: 'Address',
    city: 'City'
};

<tr>
    <td><input type="text" class="form-control" id="inputDefault"  ng-model='info.company_name' name='company_name'></td>
    <td><input type="text" class="form-control" id="inputDefault"  ng-model='info.address' name='address'></td>
    <td><input type="text" class="form-control" id="inputDefault"  ng-model='info.city' name='city'></td>
    <td><input type="text" class="form-control" id="inputDefault"  ng-model='info.state' name='state'></td>
    <td><input type="text" class="form-control" id="inputDefault"  ng-model='info.country' name='country'></td>
    <td><input type="text" class="form-control" id="inputDefault"  ng-model='info.zip_code' name='zip_code'></td>
    <td><input type="text" class="form-control" id="inputDefault"  ng-model='info.phone_number' name='phone_number'></td>
</tr>

An object, not an Array, is used to store variables in this implementation.

Answer №2

If you want to loop through an object, make sure your model is in the form of an array. Your code looks good overall, just update your Values like this:

 $scope.Values =  [
     {
       site_name: 'Site name',
       street_address: 'Street address',
       city: 'City',
       state: 'state',
       country: 'country',
       zip_code: 'zip_code',
       phone_number: 'phone_number'
    }, 
    { //next object
    }
];

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 transforming a hover menu into a clickable menu

The scenario above demonstrates that when hovering over the dropdown menu, it displays a submenu. However, I want the submenu to be displayed after clicking on the dropdown text. Could anyone provide assistance on how to change the hovermenu to a clickabl ...

Using the useState Hook: What is the best way to add a new item to the end of an array stored in the state

I'm currently working on a project using Next.js and Tailwind, where I am trying to populate an array using the useState Hook. My intention is to iterate through the array using the map function and add items to the end of the array until there are n ...

Refreshing local JSON data in Vue.js

Being fairly new to Vue.js, I encountered an issue where I am unable to update or write data in my local JSON file. Let's assume that I have a data.json file https://i.sstatic.net/GZKh5.png and I want to add a new entry to it. I am currently using ...

What is the best way to transfer information from JavaScript to a JSON database using the fetch API?

Within the userDB.json file, it appears as follows; [{ "username": "john", "xp": 5 }, { "username": "jane", "xp": 0 } ] Inside the app.js file ; async function getUsers() { le ...

Which is the best framework to transform a NextJS website into a desktop application: Electron, React-Native, or React-

After recently mastering ReactJS, I am currently utilizing it to create an application with NextJS. My goal is to make this application available as a desktop version as well. I have been introduced to Electron, React-Native, and React-Desktop, but I am u ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Terminating a client connection in Node.js using socket.io

What is the best way to terminate the socket connection on the client side? I am currently utilizing: socket.io 0.9 node.js 0.10.15 express 3.3.4 For example, when calling localhost/test -- server side var test = io .of('/test') .on(&apos ...

Understanding the optimal scenarios for utilizing inline functions in button onClick events in JavaScript/React.js

When it comes to assigning event handlers to buttons, there are various styles to choose from. Is there a specific scenario where using an inline function for the button's onClick event handler is recommended? onClick={props.handleDeleteOption(props. ...

Is it possible to use wildcards in Socket.io rooms or namespaces?

The hierarchy I am working with is as follows: Store -> Manager -> Assistant In this setup, a Manager has access to everything that the Assistant sends, while the Assistant can only access what the Manager explicitly provides. My understanding is t ...

Displaying a sneak peek of the information along with a "See More" button beneath the title in React

My goal is to create a section header followed by preview content that defaults to showing only the first few lines. The text would then fade out, with an option to expand on click labeled "Show More." This functionality is similar to how Reddit displays p ...

Display validation errors in Angular2 forms when the form items are left empty and the user tries to submit the form

In my application, I have a userForm group containing keys such as name, email, and phone. Additionally, there is an onValueChanged function that subscribes to changes in the form and validates the data. buildForm(): void { this.userForm = this.fb.gr ...

Using angularJS factory to resolve with angular-ui-route

I am having trouble implementing the $stateProvider resolve feature in my Angular project. I have created a factory called playlistsService, but for some reason, the promise returned by the factory is empty. However, when I check the data from the $http ca ...

Animate the service item with jQuery using slide toggle effect

Currently, I am working on a jQuery slide toggle functionality that involves clicking an item in one ul to toggle down the corresponding item in another ul. However, I am encountering difficulties in linking the click event to the correct id and toggling t ...

Displaying a loading indicator while a file is downloading and the page is being

Is there a way to show a loading indicator while a PDF is being generated in PHP? I redirect to a separate page for the PDF generation process, but the original page stays open and simply downloads the file once it's ready. How can I make a loading in ...

Change the attribute to read-only upon modification of the dropdown value

I have a dropdown menu with four options. My goal is to make the "number" input field readonly if the user selects either "option3" or "option4" from the dropdown. <select id="dropdown"> <option value="option1">option1</option> ...

"Exploring the Power of Logarithmic Slider with Vue and Quasar

I'm currently working on a project utilizing Vue 2 and Quasar 1, where I am attempting to develop a logarithmic slider. Initially, I managed to create a basic example using a native input slider in this code pen: https://codepen.io/tonycarpenter/pen/Z ...

An issue with modalInstance injection in AngularJS causing an error

MyAdmin.controller('AdminMasterController', ['$rootScope', '$q', '$scope', '$http', 'ApiCall', 'DTOptionsBuilder', 'DTColumnDefBuilder', '$window', 'myStorageSer ...

Employing the ng-token-auth function for logging in and submitting to an alternate URL

Currently, I am utilizing ng-token-auth along with angular/ionic to interact with a rails api. My focus right now is on the login page where I have implemented the following form: <form ng-submit="submitLogin(loginForm)" role="form" ng-init="loginForm ...

Is it necessary to specify the inputs property when defining an Angular @Component?

While exploring the Angular Material Button code, I came across something interesting in the @Component section - a declared inputs property. The description indicates that this is a list of class property names to data-bind as component inputs. It seems ...

What steps can I take to stop Highcharts from showing decimal intervals between x-axis ticks?

When the chart is displayed, I want to have tick marks only at integer points on the x-axis and not in between. However, no matter what settings I try, I can't seem to get rid of the in-between tick marks. Chart: new Highcharts.chart('<some i ...