Create A Form Container With Angular Js Component
Solution 1:
There are two basic problems need to be solved in your form container:
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;
}
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"