Program Tip

Angularjs-간단한 양식 제출

programtip 2020. 11. 25. 08:21
반응형

Angularjs-간단한 양식 제출


저는 AngularJs로 학습 곡선을 진행 중이며 실제 사용을 제공하는 예가 사실상 없다는 것을 발견했습니다.

가장 표준적인 구성 요소로 양식을 제출하고 PHP 파일로 전달하는 방법을 명확하게 이해하려고합니다.

바이올린 .

누구든지 저와 다른 Angularjs 초보자에게 도움이 될 단순하고 오염되지 않은 양식 제출에 대한 좋은 예가 있습니까?

깔끔한 형태라고 할 때 이런 말을하는 것입니다 ..

<div ng-app="myApp">

    <form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">

        First name:    <br/><input type="text" ng-model="form.firstname">    <br/><br/>
        Email Address: <br/><input type="text" ng-model="form.emailaddress"> <br/><br/>

        <textarea rows="3" cols="25" ng-model="form.textareacontent"></textarea>

            <br/><br/>

        <input type="radio" ng-model="form.gender" value="female" />Female ...
        <input type="radio" ng-model="form.gender" value="male" />Male <br/>

            <br/><br/>

        <input type="checkbox" ng-model="form.member" value="5"/> Already a member

            <br/><br/>

        <input type="file" ng-model="form.file_profile" id="file_profile"><br/>
        <input type="file" ng-model="form.file_avatar" id="file_avatar">

            <br/><br/>

        <!-- <button ng-click="save()" >Save</button> -->
        <input type="submit" ngClick="Submit" >

    </form>

</div>

내 ng-app 코드 ...

var app = angular.module('myApp', []);
app.controller('FormCtrl', function ($scope, $http) {

     var formData = {
        firstname: "default",
        emailaddress: "default",
        textareacontent: "default",
        gender: "default",
        member: false,
        file_profile: "default",
        file_avatar: "default"
    };

    $scope.save = function() {
        formData = $scope.form;
    };

    $scope.submitForm = function() {
        console.log("posting data....");
        formData = $scope.form;
        console.log(formData);
        //$http.post('form.php', JSON.stringify(data)).success(function(){/*success callback*/});
    };

 });

여기서부터 세 가지 질문은 ...

  1. 내 PHP 파일이 이것과 어떻게 상호 작용해야합니까 (php 파일의 배열에 json 문자열을 가져 오는 방법)?
  2. 체크 박스가 참인 경우 체크 박스 값을 어떻게 제출합니까?
  3. 이미지를 제출하기 위해 Angular와 함께 jQuery를 사용하여 많은 정보를 찾았습니다.이 제출에 이미 이미지 객체가 있음을 알았습니다. 어떻게 해당 데이터를 검색합니까? 이미지에 포함 할 고려 사항은 무엇입니까?

나는 명확하고 간결한 정보를 기꺼이 받아들이고 모두를위한 좋은 학습 사례를 모을 것입니다 ...

바이올린


경고 이것은 Angular 1.x 용입니다.

Angular (v2 +, 현재 버전 8)를 찾고 있다면이 답변 이나 공식 가이드를 사용 해보세요 .


원래 답변

여기에 JS 바이올린을 다시 작성했습니다. http://jsfiddle.net/YGQT9/

<div ng-app="myApp">

    <form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">

        First name:    <br/><input type="text" name="form.firstname">    
        <br/><br/>

        Email Address: <br/><input type="text" ng-model="form.emailaddress"> 
        <br/><br/>

        <textarea rows="3" cols="25">
          Describe your reason for submitting this form ... 
        </textarea> 
        <br/>

        <input type="radio" ng-model="form.gender" value="female" />Female
        <input type="radio" ng-model="form.gender" value="male" />Male 
        <br/><br/>

        <input type="checkbox" ng-model="form.member" value="true"/> Already a member
        <input type="checkbox" ng-model="form.member" value="false"/> Not a member
        <br/>

        <input type="file" ng-model="form.file_profile" id="file_profile">
        <br/>

        <input type="file" ng-model="form.file_avatar" id="file_avatar">
        <br/><br/>

        <input type="submit">
    </form>
</div>

Here I'm using lots of angular directives(ng-controller, ng-model, ng-submit) where you were using basic html form submission. Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission

BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.

For general advice on angular form submission see the cookbook examples

UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission

The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.

Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.


Sending data to some service page.

<form class="form-horizontal" role="form" ng-submit="submit_form()">
    <input type="text" name="user_id" ng-model = "formAdata.user_id">
    <input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>

$scope.submit_form = function()
            {
                $http({
                        url: "http://localhost/services/test.php",
                        method: "POST",
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        data: $.param($scope.formAdata)
                    }).success(function(data, status, headers, config) {
                        $scope.status = status;
                    }).error(function(data, status, headers, config) {
                        $scope.status = status;
                    });
            }

I have been doing quite a bit of research and in attempt to resolve a different issue I ended up coming to a good portion of the solution in my other post here:

Angularjs - Form Post Data Not Posted?

The solution does not include uploading images currently but I intend to expand upon and create a clear and well working example. If updating these posts is possible I will keep them up to date all the way until a stable and easy to learn from example is compiled.


I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().

If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

참고URL : https://stackoverflow.com/questions/19985344/angularjs-simple-form-submit

반응형