Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
SamanShafigh opened this issue Sep 4, 2015 · 6 comments

Comments

@SamanShafigh
Copy link

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
Copy link
Author

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);                
            });   
    });
})();

@danhunsaker
Copy link
Owner

For the moment, this is your best bet.

@SamanShafigh
Copy link
Author

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

@abku
Copy link

abku commented Jan 14, 2016

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

@SamanShafigh
Copy link
Author

@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);
            });
    }]);
})();

@abku
Copy link

abku commented Jan 14, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants