Skip to content Skip to sidebar Skip to footer

Create A Form Container With Angular Js Component

I am using Angular JS 1.5.6 and I would like to use only component and not directive. I have more than 5 views using a form in my application. The style of the form is exactly the

Solution 1:

There are two basic problems need to be solved in your form container:

  • Dynamic template for your form

  • Handle summit should be run outside of your component.

I solve two problems by

  • Read template via attrs property

  • Pass handler function as a binding property

Code for form component:

  angular.module('MyApp').component('myForm', {
    templateUrl: function($element, $attrs) {
      return$attrs.template; // read template file from component attribute
    },
    controller: MyFormController,
    bindings: {
      label: '@',
      summitHandler: '&'// call to function outside of component via this property
    }
  });

In MyFormController, we need handle summit event by calling to summitHandler function passed via binding property:

functionMyFormController($scope, $element, $attrs) {
      var ctrl = this;
      ctrl.summitForm = function(data) {
        // call handler with data summitedvar handler = ctrl.summitHandler();
        handler(data);
      }
}

That all for our form container component.

Now you can add my-form with:

<my-formlabel="Personal Info"template="myForm.html"summit-handler="ctrl.myFormHandler"></my-form>

Property ctrl.myFormHandler will be a function handling event in myCtl with:

ctrl.myFormHandler = function(data){
    console.log('receive test summit:' + data);
    ctrl.dataReceived = data;
}

See it run here in Plunk.

Typing in the age field, you can see it will be passed to outside of form. Extend it with more features as you want.

Solution 2:

Look at this project:

http://kelp404.github.io/angular-form-builder/

If you want to implement this yourself you will need to create a template dynamically and compile it before it's injected into the DOM. This project can be useful:

https://github.com/incuna/angular-bind-html-compile

It's directive but it will inject and compile your form elements (components or directives) for you:

<divbind-html-compile="formElements.input1"></div>

Post a Comment for "Create A Form Container With Angular Js Component"