AngularJS。将表单字段转换为 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19916485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:02:30  来源:igfitidea点击:

AngularJS. Converting form fields to json

jsonangularjs

提问by ses

Trying to understand how could be possible to write a function, (directive / controller) that would transform all my form inputsto json with current value that they have to json.

试图了解如何编写一个函数(指令/控制器),将我的所有内容转换form inputs为具有当前值的 json json

The json would have a format similar to that:

json 的格式类似于:

{    
    fields: [
          {field1: value1},
          {field2: value2},
          {field3, value3}
        ]    
}

Where to start from at least.. with no jqueryapplying?

至少从哪里开始......没有jquery申请?

回答by charlietfl

ng-modeldoes it for you. A scope variable will be created if you haven't already created it yourself

ng-model为你做。如果您尚未自己创建范围变量,则会创建它

<form name="myForm" ng-submit="submitMyForm()">
    <input ng-model="fields.name"  />
function myController($scope){
    $scope.submitMyForm=function(){
        /* while compiling form , angular created this object*/
        var data=$scope.fields;  
        /* post to server*/
        $http.post(url, data);        
    }

}

If you have the object to start with in your scope angular will 2 way bind to the input, so any values that are initially set in the scope object will show up in the input

如果您的范围内有对象开始,angular 将以两种方式绑定到输入,因此最初在范围对象中设置的任何值都将显示在输入中