Code Monkey home page Code Monkey logo

angular-dynamic-forms's Introduction

angular-dynamic-forms

Join the chat at https://gitter.im/danhunsaker/angular-dynamic-forms Build Forms in AngularJS From Nothing But JSON

Uses the MIT License. See LICENSE file for details.

Installation

Bower

The easy way.

  1. bower install angular-dynforms (add --save if you want to add the dependency to your own project - HIGHLY RECOMMENDED)

Git

The old way.

  1. Clone the project from either GitHub or BitBucket - whichever you prefer.
  2. Copy dynamic-forms.js into your project wherever your other assets reside.

Name Change

When registering this project with bower, I discovered that there's another project called angular-dynamic-forms already registered there. The project was created at the beginning of October 2014, long after this one, and I haven't yet worked out if there are any similarities in the implementation, but as I've been thinking of shortening the name of this project for a while anyway, I went ahead and registered it in bower with the shorter name. I'll be changing the repo name on GitHub and BitBucket, too, but not for several months, to give existing users time to notice the addition of full bower support. The repo will be renamed to match the name registered in bower, and the bower name will not change. It is strongly recommended to use the bower method so you can get the latest version of this project at any given time, regardless of whether I've gotten around to renaming the repo.

Use

As with any other AngularJS module:

  • include the script into your page anywhere after AngularJS itself, using whichever mechanism you use for including scripts in your project:
    <script src="bower_components/angular-dynforms/dynamic-forms.js"></script>
    require('angular-dynforms');
  • INTERNET EXPLORER: This project (as with most of Angular itself) WILL NOT work properly with IE 6 or 7. Some of the functionality can be coerced into working, but much of it will simply be broken. radio fields, for example, will have every member selected. This may be fixed in a future version, but as it's 2014, IE 6 and 7 are very low priorities, especially with XP reaching end of life. IE 8 will work, with a bit of extra setup (you can try this for IE 6 and 7 as well, but again, they probably won't work):
    <!--[if lte IE 8]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.1/json3.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/2.3.0/es5-shim.min.js"></script>
        <script>
            document.createElement('ng-include');
            document.createElement('ng-pluralize');
            document.createElement('ng-view');
            document.createElement('ng-form');
            document.createElement('dynamic-form');
            
            // Optionally these for CSS
            document.createElement('ng:include');
            document.createElement('ng:pluralize');
            document.createElement('ng:view');
            document.createElement('ng:form');
            
            // IE doesn't always run the bootstrap on its own...
            $(document).ready(function() {
              angular.bootstrap(document.documentElement);
            });
        </script>
    <![endif]-->
  • inject dynform as a dependency of your project.
    appModule = angular.module('app', ['dynform']);
    <dynamic-form template="formTemplate"
        ng-model="formData"
        ng-submit="processForm()">
    </dynamic-form>
  • populate your template with a JSON array describing the form you want to create.
    $scope.formData = {};   // JavaScript needs an object to put our form's models into.
    
    $scope.formTemplate = [
        {
            "type": "text",
            "label": "First Name",
            "model": "name.first"
        },
        {
            "type": "text",
            "label": "Last Name",
            "model": "name.last"
        },
        {
            "type": "email",
            "label": "Email Address",
            "model": "email"
        },
        {
            "type": "submit",
            "model": "submit"
        },
    ];
    
    $scope.processForm = function () {
        /* Handle the form submission... */
    };

And that's about it! Check out the demo for a more robust example, or keep reading to learn about all of the things you can do with this module.

The TL;DR Version

The Directive

You invoke the dynamic-form directive using an element (<dynamic-form></dynamic-form>) - other options (such as class, attribute, and comment) are unsupported (for now). The directive requires two attributes: an ng-model, and either a template or a template-url. The ng-model will be used to generate valid ng-model attributes for the various input controls in the template. In accordance with how AngularJS handles this attribute elsewhere, your entire form's data will be available in keys of whichever model you specify here (though nested forms are an exception, unless you specify a key in the outer form's model as the ng-model of the inner form). You must initialize this parent model to an object, or your app will break.

If you specify a template-url, the dynamic-form directive will retrieve the form template via $http and build out your form based on the response. Currently, failure is silently ignored. This may change in a later release.

You may not want to rely on the directive to retrieve your form directly - perhaps you want to do some processing on the server response before passing it to the directive for building, or maybe you need to specify a more complex $http request with advanced authentication. Or perhaps you just want to proactively handle failure to retrieve the template. Enter the template attribute. When the directive sees template, it ignores any template-url and instead uses the array identified by the template attribute. (See below for more details on this value.) At some point in the future you will also be able to dynamically update this array, and the changes will automatically be reflected in the DOM. This is currently unsupported, however, and for technical reasons, will likely not be supported at all for templateUrl arrays.

Any other attributes you specify on the dynamic-form element are copied across to the form or ng-form element that the directive builds to replace itself with. Similarly, any pre-existing contents are copied across as well, to the top of the resulting form, with the dynamically-specified controls below them. This allows you to nest dynamic-forms inside each other in the same way as ng-form (which is one reason this directive implements this pseudo-transclusion).

The dynamic-form directive makes every attempt to set up the forms it generates to be valid HTML forms, complete with the ability to have their data submitted to the server by the browser's native form submission mechanism and still have the data in the same structure that it takes on in your AngularJS models. This makes it easy to implement a fallback mode in case there is a problem with using the standard Angular methods to handle your form inputs. You will, of course, need to provide your own action and method attributes for this to work completely.

The Template

Regardless of whether it arrives via template or template-url, the form template is a fairly-straightforward JavaScript array/object. Each index/key of the template value (referred to elsewhere in this README as an ID) serves as the name and ng-model (where applicable) of the control described in the corresponding value. Each of the values, then, is an object describing a form input control. A type key identifies what kind of control to build, which in turn determines what other keys are expected. Any type that isn't supported builds a <span> containing the value of the label key, if one exists, as its content, and any other keys as attributes.

Supported Control Types

Following is a list of all currently-supported types, and then a more detailed specification of each. Links to Angular documentation in the specifications below indicate that values will be added to the Angular-defined attributes mentioned, and that Angular provides the actual functionality described there. Note that not all of these types are properly supported in all browsers, yet; there are a number of references around the web for which browsers support what.

Common Options

button

  • Renders: <button></button>
  • Additional Options:
    • None
  • Other Notes:
    • The value of label is used as the content of the <button> itself; no additional elements are created

checkbox

checklist

  • Renders: multiple <input type="checkbox"> controls
  • Additional Options:
    • options: an object containing a collection of child objects, each describing a checkbox
      • The key of each child object specifies the key to associate with the checkbox it describes
      • class: applies a specific ng-class to the current checkbox, independently of the rest
      • label: operates identically to the standard label option, but applies to a specific checkbox in the list
      • See the checkbox type for other fields supported here
  • Other Notes:
    • This is a convenience type, used to tie a group of checkbox controls together under a single model; the model holds an object, and each control sets a separate key within it
    • You can set a val on the entire checklist (it must, of course, be an object) in addition to any per-option vals; the per-option versions are set after the full checklist version, so they will override anything set to their key by the checklist itself

color

  • Renders: <input type="color">
  • Additional Options:
    • None
  • Other Notes:

date

  • Renders: <input type="date">
  • Additional Options:
  • Other Notes:

datetime

  • Renders: <input type="datetime">
  • Additional Options:
  • Other Notes:

datetime-local

  • Renders: <input type="datetime-local">
  • Additional Options:
  • Other Notes:

email

  • Renders: <input type="email">
  • Additional Options:
  • Other Notes:
    • On devices that have on-screen keyboards, the browser may modify the keyboard layout to make entering email addresses in these controls easier.

fieldset

  • Renders: <fieldset></fieldset>
  • Additional Options:
    • fields: the template for the fields which should appear in the fieldset
  • Other Notes:
    • The value of label is used to create a <legend> tag as the first child of the fieldset

file

  • Renders: <input type="file">
  • Additional Options:
    • multiple: whether or not the user can select more than one file at a time with this single control
  • Other Notes:
    • A directive is included with this module that allows file controls to properly bind to AngularJS models - the control's FileList object is stored in the model, and updating the model's value with a valid FileList object will update the control accordingly
    • Also included is an AngularJS service that wraps the browser's FileReader in a promise, so you can get the contents of the selected file for further manipulation, or even send it along in an AJAX request, and all without leaving AngularJS
    • Both of these additions are modified versions of code by K. Scott Allen and made available on the OdeToCode website; the original versions are linked above

hidden

  • Renders: <input type="hidden">
  • Additional Options:
    • None
  • Other Notes:
    • Because the underlying HTML control has so little functionality, this control only supports model and val keys

image

  • Renders: <input type="image">
  • Additional Options:
    • source: the URL of the image to display in this control
  • Other Notes:
    • The value of label is used to set the alt attribute of this control

legend

  • Renders: <legend></legend>
  • Additional Options:
    • None
  • Other Notes:
    • As a display-only control, only class, label, callback (via ng-click) and disabled are supported on this control
    • The value of label is used to set the contents of this control

month

  • Renders: <input type="month">
  • Additional Options:
  • Other Notes:

number

  • Renders: <input type="number">
  • Additional Options:
    • maxValue: the largest allowed value for this control
    • minValue: the smallest allowed value for this control
    • step: the amount by which the control can increase or decrease in value
    • Also see text below
  • Other Notes:

password

  • Renders: <input type="password">
  • Additional Options:
  • Other Notes:
    • The only real difference between this control and a text control is in the rendering, so they support exactly the same options (with the exception of splitBy, since it makes no sense to split obscured-input strings)

radio

  • Renders: multiple <input type="radio"> controls
  • Additional Options:
    • values: an object which acts as a simple list of radio options to include
      • The key of each property of this option specifies the value the model should be set to when the associated radio input is selected
      • The value of each property of this option specifies the label to use for the associated radio input
  • Other Notes:
    • Because a single radio input by itself isn't particularly useful in most cases, this control type assumes users will want to define a list of value:label pairs tied to a single model; if this is incorrect, you can still create radio controls with just one value:label each, and then tie them together using the model key
    • The directive doesn't prevent you from applying a label to the entire collection of input controls created by this control type - the entire div containing them will be wrapped in a <label> tag; keep this in mind when building style sheets

range

  • Renders: <input type="range">
  • Additional Options:
    • step: the amount by which the control can increase or decrease in value
    • Also see number above
  • Other Notes:
    • By default, this control seems to provide its values to AngularJS as strings. This might be due to Angular (as well as the browser) handling them as regular text controls internally. Among its other minor tweaks, this module contains a very simple directive to override the default $parsers mechanism for range controls and convert these values back to numbers (floats, in case your step is not an integer).
    • May not be supported in all browsers

reset

  • Renders: <button type="reset"></button>
  • Additional Options:
    • None
  • Other Notes:
    • As with button, the value of label provides the control's contents
    • AngularJS doesn't seem to monitor the reset event, so your models wouldn't normally be updated when the form is cleared in this way; while this control is strongly dis-recommended in most cases, this directive supports it, so code is included that monitors and properly handles these events (NOTE - this feature has not been widely tested; please report any issues on GitHub or Bitbucket)

search

  • Renders: <input type="search">
  • Additional Options:
  • Other Notes:
    • All browsers support this because it works exactly like a text control. The idea is that search boxes will be styled differently, and on some devices might even support additional input methods, such as voice recognition. You'll probably want to tie these controls to some kind of search mechanism in your app, since users whose browsers do render them differently will expect them to act accordingly.

select

  • Renders: <select></select>
  • Additional Options:
    • autoOptions: see ng-options
    • empty: if not false or undefined, specifies the display value (contents) of an empty option, and tells the directive to include it in its output
    • multiple: if not false or undefined, allows the user to select more than one option at one time
    • options: an object containing a collection of child objects, each describing an option to include in the select list
      • The key of each child object gives the value of the associated option
      • disabled: see ng-disabled
      • group: adds the option to an optgroup whose label is the value of the group key
      • label: the display value (contents) of the option
      • slaveTo: see ng-selected
  • Other Notes:
    • An unreleased prototype version of this module (which used a combination of ng-repeat and ng-switch instead of a directive) specified four different control types for the functionality provided by this one - one for normal lists, one for grouped lists, one for multi-select lists, and one that combined multi-select with group support; this version is much cleaner about its approach - multi-select is the 'flag' option multiple, and groups are enabled by simply defining them with their associated values
    • Note that only one of options and autoOptions will be honored by this module - if you specify autoOptions, options is completely ignored; keep this in mind when building your forms because the actual values will have to be specified in a separate object

submit

  • Renders: <button type="submit"></button>
  • Additional Options:
    • None
  • Other Notes:
    • As with button, the value of label provides the control's contents

tel

  • Renders: <input type="tel">
  • Additional Options:
  • Other Notes:
    • There is currently no validation support for this control in nearly any browser, and AngularJS doesn't provide any by default. This is mostly because telephone numbers are tricky beasts, especially with the differences between how these numbers are allocated from one part of the world to another. And that's before we start getting messy with things like VoIP "numbers".

text

  • Renders: <input type="text">
  • Additional Options:
  • Other Notes:
    • This control serves as the base template for nearly all the other form input controls defined by HTML - as such, most of the controls supported by this directive support these options as well, leading their entries to refer here

textarea

  • Renders: <textarea></textarea>
  • Additional Options:
  • Other Notes:
    • While the syntax used to define them in raw HTML differs to some extent, the only practical difference between text and textarea controls is the multi-line support offered by textarea - therefore, the options available to each are identical

time

  • Renders: <input type="time">
  • Additional Options:
  • Other Notes:

url

  • Renders: <input type="url">
  • Additional Options:
  • Other Notes:
    • Similar to the email type, some browsers will alter on-screen keyboards when this control type is selected in such a way that URL entry is simplified; AngularJS, meanwhile, enforces the requirement that the value be a valid URL, even if the browser does not

week

  • Renders: <input type="week">
  • Additional Options:
  • Other Notes:

Acknowledgements

Alternatives

If this project isn't for you (it's not very mature, yet, so there are plenty of reasons it may not be a good fit for your projects, yet), there are some other ways to go about the same basic thing. They each have their own benefits and drawbacks, but I'll let their own developers speak to those, especially as I haven't tested any, yet. Here are a few; let me know if you're aware of others:

  • JSON Form - A jQuery-based library for converting JSON Schemas into HTML forms; a mature option with many advanced features, though centered around Twitter Bootstrap.
  • Angular Schema Form - An Angular implementation of (not wrapper for) JSON Form.
  • Alpaca - Another jQuery-based library, it boasts many of the same features as JSON Form.
  • MetaWidget - Apparently automated, based on existing infrastructure, rather than controlled by code. Boasts compatibility with many languages and frameworks, including AngularJS, Java Swing, native Android, and others.
  • inputEx - A YUI3 library offering.
  • "The Other" ADF - Wallace Breza's project with the same name this one started with.

Issues And Assistance

If you notice a problem, let me know about it on GitHub or Bitbucket!

Any and all help is welcome; just fork the project on either GitHub or BitBucket (whichever you prefer), and submit a pull request with your contribution(s)!

angular-dynamic-forms's People

Contributors

danhunsaker avatar gitter-badger avatar jandetlefsen avatar jupiterzzz avatar kynan avatar pranay92 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

angular-dynamic-forms's Issues

How to add callbacks to button types?

Sorry for all the questions ...

I'm just wanting to add a callback per the docs to a button. Can you share a working example please? when I try, the ng-click attribute is never getting added to the button. If i just set ng-click to some dummy string, it will get added to the attribute list for the button. but if I have it as a function like below, the function executes when the page loads, but there is no ng-click ever added to the element.

// This one will work but the function is not executable.. so nothing happens when you click the button
"cameraButton": {
"type": "button",
"label": "button",
"callback": 'alert()'
},

// This one will not cause ng-click to be added to the element at all
"cameraButton": {
"type": "button",
"label": "button",
"callback": function (e) {
console.log("clicked");

},

I did step through the debugger and the code is getting executed to add the 'ng-click' attribute, but the button element will never actually have it - any function added there just gets executed once when it loads.

How to apply a directive into dynamic input?

I'm very confused to apply a directive into a dynamic input.

My JSON is like this:

      "text": {
        "attributes": {
          "own-validator": "something"
        },
        "type": "text",
        "placeholder": "text",
        "required": "true"
      },

My directive:

.directive('ownValidator', function () {
return {
restrict: 'A',
scope: {
'inputDefinition': '=ownValidator'
},
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
console.log(scope, element, attrs, ctrl)
}
}
})

So when the input is rendered and I try to write something into the input, error console's is showing.

What is the best way to apply a directive?
Thanks a lot!

Test Issue

This is a test. It will be closed and/or deleted.

Help needed with loading the Dynamic form on Button Click

Hi,

I am following this dynamic form generation to read my JSON response and load the form exactly the way it is done in your code. On load the screen renders successfully and I can see my form.
Now, one of the tags in the form is a button on click of which I need to modify my json object and then would like my screen to be rendered from this updated json object.
So just to give an example,
On load my screen looks like this:

ใ€ŠADDใ€‹ // ADD is a button

On click of ADD button, I would like to update my screen as follows:

ใ€ŠADDใ€‹

I tried to do this by updating my json object on click of the button, but after the update screen remains as it is because the dynamic-form directive doesn't load again.

I would appreciate if you can please suggest a way to do this.

Thank you,
Ravi

"TypeError: Cannot read property 'nodeName' of undefined" from dynamic-forms.js:304:114

I get this error using Angular v1.2.15 & jQuery v1.11.1.

The while statement from line 303 never evaluates to false here so the next line tries to get .nodeName out of an empty array.

For whatever reason, even though iterElem.parent() and angular.element() will both equal [] at some point, Angular doesn't believe they're equal.

Changing 303:

while (!angular.equals(iterElem.parent(), $document)
    && !angular.equals(iterElem.parent(), angular.element())) {

to:

while (!angular.equals(iterElem.parent(), $document)
    && iterElem.parent().length)) {

would fix, as a suggestion. Or something else that stopped before going all the way up the tree. Or comparing them differently. IDK.

Unable to create show page of a form

Hi Daniel,

Please suggest me one thing. Your module is working well for creating form. But I am developing create,show and update page for every entity like invoice, bill an others. So I want to show the value of all fields as label taken as input from form create page.

Please suggest me is there scope in your awesome module for creating show page . I have to show only labels no input, no checkbox .. only labels.

Thanks in advance,
Pushpendra

Not a problem, but a list of questions/howtos

I'd like to ask you about supporting these things (yes/no and if yes, how to approach that)?

  1. Field dependencies
  • show/hide field depending on other field values
  • make field required or optional, depending on other values
  • show/hide entire form sections dynamically
  • change list of available select options depending on other values
  • Custom validation
    provide custom validation rules that would take multiple field values into consideration

Thanks!

Is it possible to render horizontal forms ?

Hey there ,
Thanks for this awesome stuff,

Is there any way i can render forms horizontally ? Usually a user would not like to scroll too much if the forms are too long.

Please reply!

Sort and custom style!

Hi,
Now i want to sort my form element, like:

{
"type": "text",
"model": "username",
"label": "Username",
"placeholder": "Your username",
"order" : 1,
"style" : "width:200px;background-color: #fff000"
....
}

Please tell me how?

Regards!

How to add more objects

Planning to add more objects like Grid, Tabs, menu with the same method. your help will be greatly appreciated.

Please provide some guideline to start on this. i have a small team to contribute on this.

ng-repeat support

It seems that is not possible to have the directive inside the ng-repeat, like the following code

<accordion-group heading="{{nodetype.type}}" ng-repeat="nodetype in nodetypes">
    <dynamic-form class="col-md-12" template-url="{{nodetype.file}}" ng-model="{{nodetype.data}}" ng-submit="{{nodetype.process}}()">
  </dynamic-form>
</accordion-group>

Does it support field validation with error message?

It seems not support data validation with error message. For example, my json data has a collection of metadata for validation rules such as required, length range, number range, regex. How is it easily modified to support validation to display error message?

Callback event not working

Hi,
I have used the dynamic forms plugin and it is working great.Although i came across that callback function is not working.
Example : "checkbox": {
"type": "checkbox",
"label": "checkbox",
"callback": "myFunction"
}
and i defined it in app.js like
$scope.myFunction= function() {
console.log('on change event');
};
Even though i applied callback function on button as well.

Please let me know if i missed something.

I would truly appreciate if you can check into this and provide the right direction.

Best Regards,
Vikas Nawal

Bootstrap support

Hi,

did you consider theming support, aka optionally supporting Bootstrap? If you have some advice for me, I'd volunteer implementing it.

How to create dynamic forms using multi dimensional array.

Hi ,
I want to create dynamic forms using multi dimensional array.Although I am able to create forms using one dimensional array and its really good.
"settings1": {
"input1": {
"label": "test",
"type": "STRING",
},
"input1": {
"label": "test",
"type": "STRING",
}
},
"settings2": {
"input1": {
"label": "test",
"type": "STRING",
},
"input1": {
"label": "test",
"type": "STRING",
}
},
"settings3": {
"input1": {
"label": "test",
"type": "STRING",
},
"input1": {
"label": "test",
"type": "STRING",
}
}
Please advice.How can i achieve this functionality.

Yet another idea for an enhancement: a "dynamic" dynamic form ??

So, one thing that would be cool is to have the ability to 'clone' a given element. Like perhaps have an attribute 'clonable": true, and that can be configured on any supported form field type that you support. If we see this, have a button like on the bottom of it called like 'add one more' or a plus sign or whatever. So once can click it and will make another form element type of the same type. A 'dynamic' dynamic form ;)

thoughts? the model name could just have the number added to it as it's added maybe??

Dynamically compile html with dynamic-form directive in Internet explorer.

Unable to compile the dynamic-form directive in ie8. When i have this directive in my index file, this works fine, but when i compile this dynamically, $compile function gives this an error as it (ie8) does not support the directives with tags and the solution that angular suggests i.e. (document.createElement('dynamic-form') ) in index. This works fine for index but any solution when we have to do this for an html which is loaded on the go.

Control markup

Hi,
Thanks for this, it is working very well so far.
My problem is that I'm not sure if and how I can control the output markup to play well with my app, based on ionic.
That means that instead of:

<label>
  First Name
  <input type="text" name="first" ng-model="formData['first']" class="ng-pristine ng-valid">
</label>

I would like to have

<label class="item item-input">
  <span class="input-label">First Name</span>
  <input type="text" placeholder="First Name" ... >
</label>

How would I approach this?
Thanks

Pre-processing form data

Hey!

I am getting my data from a server and I have to pre-process is before it can be used in dynamic-forms.
My problem is, that the data is somehow not available in the dynform.

The controller looks like this:

myControllers.controller('ProjectUserInfoCtrl', ['$scope', '$http', '$routeParams', 'Project', 'ProjectField',
  function($scope, $http, $routeParams, Project, ProjectField) {

      $scope.formData = {};
      $scope.formTemplate = [];

    var project = Project.get({ projectId: $routeParams.projectId }, function(data) {
        $scope.project = data.projects;
    });

    var fields = ProjectField.get({ projectId: $routeParams.projectId }, function(data) {
        $scope.fields = data.fields;
        $.each($scope.fields, function(k, v) {
            $scope.formTemplate.push({
                "type": "text",
                "label": v.name,
                "model": v.name
            });
        });
    });
}]);

Thanks in advance!

the 'disabled' and 'readonly' fields

I'm trying to set 'disabled: $scope.processing' (or 'readonly: $scope.processing) but the form does not update as I update $scope.processing.

e.g.,
fields: [
{
type: "text",
readonly:$scope.processing,
model: "name",
label: "name*:"
},

Am I doing something wrong?

keeping order using a json object is a bit of a headache

Trying to use you module.
I am generating the form template dynamically using python. However, I want to have control over the order in which the form items appear.
I think using an array of objects could be a better approach ?

Sander.

Checklist

Hi -- I'm trying to populate my check list from stored json data
region: {1:true}

But it isn't being checked in the form;

    var dynamicForm =  {
        "region": {
            "type": "checklist",
            "label": "Region",
            "options": {
                "1": {
                    "label": "North East"
                },
                "2": {
                    "label": "All"
                },
                "3": {
                    "label": "South Texas"
                },
                "4": {
                    "label": "Permian"
                },
                "5": {
                    "label": "Mid Continent"
                },
                "15": {
                    "label": "West"
                }
            }
        }
    };

Any thoughts ?
I have other components and they are populating correctly.

[email protected]

Unable to create tabs from json

Hello,

Thank you very much for this nice work. Please help me, I want to create complete page from your module. Please suggest me a way to create tabs from json, thats is provided to your awesome form creator module.

Thanks,
Pushpendra

Selects have weird option tag (ex. <option value="? string:30 ?" />) when model has data

If the select input's model contains data, then angular creates an odd option tag with a cryptic value and no label.

Example:
<option value="? string:30 ?" />

This results in a blank option being displayed at the top of the option list. Strange enough, this option will then disappear once another option is selected in the browser.

See link below for similar issue and resolution:
http://stackoverflow.com/questions/16783294/angular-adds-strange-options-into-select-element-when-setting-model-value

Unknown provider: dynformProvider <- dynform <- LoginCtrl

"Error: [$injector:unpr] Unknown provider: dynformProvider <- dynform <- LoginCtrl
http://errors.angularjs.org/1.4.8/$injector/unpr?p0=dynformProvider%20%3C-%20dynform%20%3C-%20LoginCtrl
minErr/<@http://127.0.0.1:8000/app/bower_components/angular/angular.js:68:12
createInjector/providerCache.$injector<@http://127.0.0.1:8000/app/bower_components/angular/angular.js:4334:19
getService@http://127.0.0.1:8000/app/bower_components/angular/angular.js:4482:39
createInjector/instanceCache.$injector<@http://127.0.0.1:8000/app/bower_components/angular/angular.js:4339:28
getService@http://127.0.0.1:8000/app/bower_components/angular/angular.js:4482:39
invoke@http://127.0.0.1:8000/app/bower_components/angular/angular.js:4514:1
instantiate@http://127.0.0.1:8000/app/bower_components/angular/angular.js:4531:27
$ControllerProvider/this.$get</<@http://127.0.0.1:8000/app/bower_components/angular/angular.js:9197:18
ngViewFillContentFactory/<.link@http://127.0.0.1:8000/app/bower_components/angular-route/angular-route.js:977:26
invokeLinkFn@http://127.0.0.1:8000/app/bower_components/angular/angular.js:8841:9
nodeLinkFn@http://127.0.0.1:8000/app/bower_components/angular/angular.js:8335:1
compositeLinkFn@http://127.0.0.1:8000/app/bower_components/angular/angular.js:7731:13
publicLinkFn@http://127.0.0.1:8000/app/bower_components/angular/angular.js:7611:30
createBoundTranscludeFn/boundTranscludeFn@http://127.0.0.1:8000/app/bower_components/angular/angular.js:7749:1
controllersBoundTransclude@http://127.0.0.1:8000/app/bower_components/angular/angular.js:8362:18
update@http://127.0.0.1:8000/app/bower_components/angular-route/angular-route.js:935:25
$RootScopeProvider/this.$get</Scope.prototype.$broadcast@http://127.0.0.1:8000/app/bower_components/angular/angular.js:16374:15
commitRoute/<@http://127.0.0.1:8000/app/bower_components/angular-route/angular-route.js:619:15
processQueue@http://127.0.0.1:8000/app/bower_components/angular/angular.js:14792:28
scheduleProcessQueue/<@http://127.0.0.1:8000/app/bower_components/angular/angular.js:14808:27
$RootScopeProvider/this.$get</Scope.prototype.$eval@http://127.0.0.1:8000/app/bower_components/angular/angular.js:16052:16
$RootScopeProvider/this.$get</Scope.prototype.$digest@http://127.0.0.1:8000/app/bower_components/angular/angular.js:15870:15
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://127.0.0.1:8000/app/bower_components/angular/angular.js:16160:13
done@http://127.0.0.1:8000/app/bower_components/angular/angular.js:10589:36
completeRequest@http://127.0.0.1:8000/app/bower_components/angular/angular.js:10787:7
requestLoaded@http://127.0.0.1:8000/app/bower_components/angular/angular.js:10728:1
"

What does this error mean?

How to populate my form template and data with a JSON array dynamically

Hi

I have an api service which reterns a JSON like this

  {"form":{
     "template":[
          {"type":"text","model":"title","label":"","required":true},
          {"type":"textarea","model":"description","label":"","required":true},
          {"type":"number","model":"price","label":"","required":true},
          {"type":"choice","model":"available","label":"","required":true}],
     "data":{"title":"","description":"","price":"","available":"1"}}
 }

Then I want to use this JSON to generate my form dynamically, my code is like this

(function(){
    var app = angular.module('app', ['dynform']);

    app.controller('AppCtrl', function ($http, $scope) {
        $http.get('../api/product/form/1').
            success(function(data) {
                $scope.stdFormData = data.form.data;
                $scope.stdFormTemplate = data.form.template;
            });   
    });
})();

But it dose not work, much appreciate if can help

Add form fields dynamically

Hey,

it would be great to have possibility adding fields dynamically from code. Currently I don't see such functionality in source. It would be even better to have dynamic adding of another nested forms through template modifying.
I could take this task on myself if you'd like.

support for ng-grid

Dan,

We are extensively using this framework. There is one requirement, where we need to support ng-grid.

It looks doable. Any recommendations from your side will help me.

Thanks
Krishna

Usage of file input unclear

Hi !
I've been using dyn-form for a while and it's great, it helps me a lot ! So thanks !

One thing I didn't use so far was the <input type="file"/>, and I had trouble using it. Your readme file misses maybe some usage example (or I missed it)

  1. Unclear if you have to use the "callback":"readFile()" (ng-change) or "attributes": {"on-change":"readFile()"} (it's the latter)
  2. Don't forget to had fileReader injected in your controller
  3. In the example linked in your readme, the function is fileReader.readAsDataUrl in your plugin it's fileReader.readAsDataURL (URL full caps ^^)

Example for one image file :

$scope.formData = {};
$scope.imageSrc = ""

 $scope.formTemplate = [
    {
        "type": "file",
        "model": "image",
        "label": "Image",
        "attributes": {"on-change":"readFile()"}
    }
];

$scope.readFile = function () {
    fileReader.readAsDataURL($scope.formData["image"][0], $scope)
    .then(function(result) {
        //display the image on file change
        $scope.imageSrc = result;
    });
};

// ... do some stuff
<dynamic-form template="formTemplate"
        ng-model="formData"
        ng-submit="processForm()">
</dynamic-form>

<!-- image preview -->
<img ng-src="{{imageSrc}}"/>

Not much but if it can help people (like me) understand better how it works without looking to the source file, I leave it here !

Really needs ability to group a set of inputs like most paper forms do

I love this first of all. just what i need...

Only thing that would be awesome on top of this is to simply add basic 'fieldset' grouping and have it be titled so could be like

Residential Property Only -----
input 
input
input
---------------------------------------

and ideally be able to have a checkbox to turn a section of a form on and off. like collapse/expand of a section of a form you know?

I'm tempted to dig into it and figure out way to add this to your directive, but I know you may already have been working on this ...

Change the standard multiple element

Hi,

thank you for this amazing framework !
I'm trying to change the default multiple behavior.
I want to have a select element and a button below.
When i click on the button ("Ajouter"), the current selected element is appended to a div element below the button.
I implemented the mechanism with the framework, it works well:

image
But there is no connection with the model. The data binding is not occuring.
I changed those lines:

Line 119:

if (!(angular.isDefined(field.multiple) && field.multiple !== false)) {
                  newElement.attr('ng-model', bracket(field.model, attrs.ngModel));
                  // Build parent in case of a nested model
                  setProperty(model, field.model, {}, null, true);
                  }

Line 214:

if (angular.isDefined(field.multiple) && field.multiple !== false) {
                      field["classname"] += " multiple "; 
                  }

Line 308:

 newElement = newElement.wrap('<label class="col-xs-12"></label>').parent();
  newElement.prepend(document.createTextNode(field.label + ' '));

 if (angular.isDefined(field.multiple) && field.multiple !== false) {

                        newElement.append("<div class='col-xs-12 btn btn-default' data-textmultiple='"+field.id+"'>Ajouter</div>");
                        var div = angular.element("<div class='"+field.id+"_multiple' value='myinput'/>");
                                //The binding doesn't work :/
                        div.attr("ng-model",bracket(field.model, attrs.ngModel));
                        newElement.append(div);
                    }

Is there something else to change to have data-binding with the div ?

No Documentation for Attributes / ID Attribute Not Supported

The documentation is pretty good, and I love the library, but there does not appear to be any example for how to add attributes. The documentation just says that you apply key:value pairs but does not provide an example of the syntax.

Could you please provide an example?

Also, it might be useful if developers could apply an ID directly to a particular item. It does not appear that ID is supported.

Thank you!

Confliction with jquery

Hello,

         I am using jquery ui and jquery obvously.
         But I am getting following error -
          TypeError: Cannot read property 'nodeName' of undefined
at  while (!angular.equals(iterElem.parent(), $document) && !angular.equals(iterElem.parent(), angular.element())) {

      ie. its gettting  (angular.equals(iterElem.parent() and( $document) as different while they are same means iterElem is html tag.

Please suggest me the way.

Thanks in advance,
Pushpendra

type file accept specific filetypes

Hey, is there a way to restrict the file types accepted by a input type=file or the maximum file size (for example accept only pdf's under 30mb) ?

Issue when putting templates into an array

Hi
When I put templates into an array, then use ng-repeat with , I get some error message (TypeError: undefined is not a function
at m.extend.attr (http://localhost:8080/app/shared/vendor/jquery-1.11.1/jquery-1.11.1.min.js:4:10092)). I suspect this is because angular adds fields into arrays.

e.g.

If I add "if (id === '$$hashKey') { return; }" in your buildFields function, this seems to fix it...tho i'm not sure if this is the right fix.

Alternatively, if I add "track by $index" into my ng-repeat, this also seems to fix it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.