angular-dynamic-forms icon indicating copy to clipboard operation
angular-dynamic-forms copied to clipboard

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

Open SamanShafigh opened this issue 10 years ago • 6 comments

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

SamanShafigh avatar Sep 04 '15 02:09 SamanShafigh

I try something like this and it works for me, I am not sure if it is ok or we already have a proper way of doing this.

In my html I have something like

<div id="my-form"></div>

Then in controller I have

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

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

                var element = angular.element(document.getElementById("my-form"));
                element.html('<dynamic-form class="col-md-12" template="stdFormTemplate" ng-model="stdFormData"></dynamic-form>');
                $compile(element.contents())($scope);                
            });   
    });
})();

SamanShafigh avatar Sep 04 '15 06:09 SamanShafigh

For the moment, this is your best bet.

danhunsaker avatar Sep 04 '15 07:09 danhunsaker

Thanks danhunsaker, I am glad, BTW thanks for the package, It is so nice so far.

SamanShafigh avatar Sep 04 '15 10:09 SamanShafigh

@SamanShafigh and @danhunsaker How did you get this to work. The form does not submit to a url. Can you please help?

abku avatar Jan 14 '16 01:01 abku

@abku I put my codes here, then you can see what is your issue.

./dynamic-forms.html

<!doctype html>
<html ng-app="app" id="ng-app">
    <head>
        <title>Hello AngularJS</title>
        <link rel="stylesheet" href="./css/bootstrap.min.css">
    </head>
    <body ng-controller="AppCtrl" ng-cloak="">
        <div id="my-form"></div>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
        <script src="./components/angular-dynforms.js"></script>
        <script src="./services/shoppingService.js"></script>
        <script src="./controller/dynamic-forms.js"></script>
    </body>
</html>

./services/shoppingService.js

(function() {
    var ShoppingService = angular.module('ShoppingService', []);
    ShoppingService.service('ProductService', ['$http', function ($http) {
        //simply returns the contacts list
        this.getForm = function () {
            return $http.get('../api/product/form/76'); // it should be your URL
        };
        this.postForm = function (formData, formName) {
            return $http({
                url: "../api/product/post",
                data: serializeData(formData, formName),
                method: 'POST',
                headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
            });
        };

        function serializeData(data, formName) { 
            // If this is not an object, defer to native stringification.
            if (!angular.isObject(data)) { 
                return((data == null) ? "" : data.toString()); 
            }
            var buffer = [];
            // Serialize each key in the object.
            for (var name in data) { 
                if (!data.hasOwnProperty(name)) { 
                    continue; 
                }
                var value = data[name];
                buffer.push(
                   formName + "[" + encodeURIComponent(name) + "]=" + encodeURIComponent((value == null) ? "" : value)
                ); 
            }
            // Serialize the buffer and clean it up for transportation.
            var source = buffer.join("&").replace(/%20/g, "+"); 
            return(source); 
        }                
    }]);
})();

./controller/dynamic-forms.js

(function(){
    var app = angular.module('app', ['dynform', 'ShoppingService']);
    app.controller('AppCtrl', ['$scope', '$http', '$compile', 'ProductService', function ($scope, $http, $compile, ProductService) {
        ProductService.getForm()
            .success(function (data) {
                $scope.formTemplate = data.form.template;
                $scope.formData = data.form.data;

                $scope.processForm = function () {
                    ProductService.postForm($scope.formData, data.form.name)
                        .success(function(data){ 
                            console.log("OK");
                        })
                        .error(function(data){
                            $scope.formTemplate = data.form.template;
                            $scope.formData = data.form.data;

                            var element = angular.element(document.getElementById("my-form"));
                            element.html('<dynamic-form template="formTemplate" ng-model="formData" ng-submit="processForm()"></dynamic-form>');
                            $compile(element.contents())($scope);                            
                        });
                };

                var element = angular.element(document.getElementById("my-form"));
                element.html('<dynamic-form template="formTemplate" ng-model="formData" ng-submit="processForm()"></dynamic-form>');
                $compile(element.contents())($scope);
            });
    }]);
})();

SamanShafigh avatar Jan 14 '16 02:01 SamanShafigh

@SamanShafigh Thank you very much!!!! That works perfectly. Do not know what I did wrong but copy pasted and it works 100%.

abku avatar Jan 14 '16 03:01 abku