简体   繁体   English

从表单输入创建对象以传递给控制器​​方法

[英]Create object from Form inputs to pass to controller method

I have an array of jobs in my js/controller. 我的js /控制器中有一系列工作。 Each job object in the array has attributes like jobName, company, city, etc. Is it possible by submitting a form with inputs for the attributes to make it into a job object and then push it into the jobs array in the controller? 数组中的每个作业对象都具有诸如jobName,company,city等属性。是否可以通过提交带有属性输入的表单来使其成为作业对象,然后将其推入控制器中的jobs数组中?

So for example, I have a form and I input Software Developer, StackOverflow, NY. 例如,我有一个表单,我输入了纽约州StackOverflow的软件开发人员。 Can I wrap the form into an object with the correct attributes and then pass it into the array of jobs in the controller to view it on the view? 我可以将表单包装到具有正确属性的对象中,然后将其传递到控制器中的作业数组中以在视图中进行查看吗?

Here's my form code so far... 到目前为止,这是我的表单代码...

        <form name="jobForm" ng-submit="list.addJob(jobForm)">
                <div class="form-group" id="test">
                    <label>Job Name:</label>
                    <input ng-model="jobName" type="text"/>
                </div>
                <div>
                    <label>Company:</label>
                    <input ng-model="companyDescription" type="text"/>

                    <div><button type="submit">Enter job entry</div>
                </div>

                <!-- this is where the live preview is. ng-model in the input binds it to these values -->
                <blockquote>
                <h4><u>Live Preview</u></h4>
                    <b>Job Name:</b> {{jobName}}
                    <div><b>Company:</b>{{companyDescription}}</div>
                </blockquote>
      </form>

So I want to create a JOB object using the jobName and companyDescription's inputs as the object's name and company attribute. 因此,我想使用jobName和companyDescription的输入作为对象的名称和公司属性来创建一个JOB对象。 How can I do this? 我怎样才能做到这一点? OR am i using a wrong approach. 还是我使用了错误的方法。 Thank you for the help! 感谢您的帮助!

For starters there is a golden rule that ng-model should always be an object property to begin with ... or you can run into lots of child scope problems due to inheritance 对于初学者来说,有一个黄金法则: ng-model应该始终是一个对象属性...否则由于继承,您可能会遇到很多子范围问题

So your whole issue is simplified by not using individual scope properties and using one object for all the ng-model in the form to begin with 因此,通过不使用单个范围属性,而以表格开头的所有ng-model使用一个对象来简化整个问题

$scope.job={}
<input ng-model="job.jobName" type="text"/>
<input ng-model="job.companyDescription" type="text"/>

Then when you need to send that to server it is as simple as doing 然后,当您需要将其发送到服务器时,就像这样做一样简单

$http.post(url, $scope.job).then(func....

or pushing to another array 或推到另一个数组

  $scope.allJobs.push($scope.job);
  $scope.job = {} // reset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM