Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 645
Alexander Trauzzi Avatar asked Jun 03 '14 14:06

Alexander Trauzzi


People also ask

What is [( ngModel )]?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.

Which module should be imported to work with NG model?

The ngmodel directive is not part of the Angular Core library. It is part of the FormsModule library. You need to import the FormsModule package into your Angular module. If you want to create a form in angular app then you need to import FormsModule from @angular/forms library.

What is the purpose of name in ngModel?

name: An alternative to setting the name attribute on the form control element. See the example for using NgModel as a standalone control. standalone: When set to true, the ngModel will not register itself with its parent form, and acts as if it's not in the form.


1 Answers

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

like image 57
Marc Kline Avatar answered Nov 09 '22 23:11

Marc Kline