Getting [Object object] when using ng-model on a named form

All we need is an easy explanation of the problem, so here it is.

If I have the following:

<form
    id="registration"
    name="registration"
    method="POST"
>

    <input
        type="text"
        name="first_name"
        id="first-name"
        ng-model="registration.first_name"
        placeholder="First name"
    />

When my form displays, fields configured as above end up having [Object object] inside of them for their initial value.

What am I doing wrong here and what’s the correct way to get two-way binding inside of a form?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Setting the name attribute on a form creates a scope object which is useful for validation but is not meant to be used for the ng-model attributes of inputs.

If you use a separate scope variable for ng-model, it will work as you expect:

<form
    ...
    name="reg"
    ...
>

<input
    ...
    ng-model="registration.first_name"
    ...
/>

Demo

Method 2

I guess either the registration scope is not initialized or registration.first_name is an object.

Have a look at this plunker: http://plnkr.co/edit/bdbs0XVB8hZSodOTYyM4?p=preview

Initialize the registation model either in controller or using ng-init ng-init="registration = {}"

If registration.first_name is an object then this will be displayed as [Object object]. You have to supply a proper string value as model to the ng-model

Method 3

Angularjs Form showing [object Object] on load in form fields

I am guessing, it will show this error, only if your form name and ng-model name (value) are same

like

 <form name="userform">-------
 <input ng-model="userform.firstname">

change your form name or your ng-model value to user or some xyz

Method 4

If you don’t register a controller in ng-controller, you can remove name=”registration” from form, because controller has init with forms, i try and works.

plnkr.co/edit/JK3utpe1eERrJeoveaCQ?p=preview

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply