Search code examples
angularjsangularjs-forms

How to use form and ng-form together?


I want to use form and ng-form together. I have a markup like this:

<form 
name="createCampaignForm"
ng-submit="submitCreateCampaignForm(createCampaignForm.$valid)"
novalidate>
<myinput
  form="createCampaignForm"
  label="Campaign Name"
  name="name"
  type="text"
  ng-model="model.createCampaign.name"
  placeholder="Folow up, cart abandonment etc..."
  required="true"></myinput>
</form>

myinput is a component:

app.component('myinput', {
  templateUrl: 'components/input.html',
  transclude: true,
  bindings: {
    disabled: '<',
    required: '<',
    ngModel: '=',
    form: '=',
    label: '@',
    placeholder: '@',
    type: '@',
    name: '@',
  },
  controller: function () {
  }
});

And the component template:

<div
  ng-form
  name="{{ $ctrl.form }}">
  <label>
    {{ $ctrl.label }}
    <small ng-if="$ctrl.required">(required)</small>
  </label>
  <input
    ng-model="$ctrl.ngModel"
    name="{{ $ctrl.name }}"
    type="{{ $ctrl.type }}"
    placeholder="{{ $ctrl.placeholder }}"
    required="{{ $ctrl.required }}"
    class="form-control form-control--block form-control--primary">
</div>

I want to access myinput's validation state like createCampaignForm.name.$invalid.

When I add form attribute to myinput, the app acts like it's in an infinite loop. Page loading but it don't finish. And there is no error in browser console.

How can I achieve this?

For example, I have a form, it contains 3 myinput inside it. And I should be able to access all the myinputs' validation state like createCampaignForm.name.$valid createCampaignForm.status.$error etc...


Solution

  • I don't know why but I changed ng-form attribute and problem solved.

    I changed this:

    <div
      ng-form
      name="{{ $ctrl.form }}">
    

    To this:

    <div
      ng-form="$ctrl.form">