Evan_HZY
Evan_HZY

Reputation: 1024

Submitting a form in AngularJS?

I have a template like this:

<div><form id="appForm" method="POST" action="{{form.formActionAttr}}">
            <table class="form-table">
                <tr>
                    <td>
                        <input name="input1" type="hidden" value="{{form.input1}}"/>
                    </td>
                </tr>
                <tr>
                    <td>
                        <input name="input2" type="hidden" value="{{form.input2}}"/>
                    </td>
                </tr>
            </table>
        </form></div>

here is the controller:

function SamlFormController($scope, $sce, metadataService) {
    $scope.form = {};
    $scope.form.formActionAttr = $sce.trustAsResourceUrl('some.url');
    $scope.form.input1 = 'input1';
    $scope.form.input2 = 'input2';

    $scope.submitForm = function() {
        document.getElementById('appForm').submit();
    };
    $scope.submitForm();
}

Here is my intention: the controller run the submitForm() method, which send a HTTP POST request to the form.formActionAttr url.

But with the codes above, the action="{{form.formActionAttr}}" is not populated yet when the $scope.submitForm() is called.

How do I fix this issue?

Thanks in advance :-)

Upvotes: 0

Views: 60

Answers (1)

Henri Benoit
Henri Benoit

Reputation: 725

The problem is that the url will only be set after you application has really initialized. So you need to push the change to a later stage. You can easily do this using the $timeout service:

function SamlFormController($scope, $sce, $timeout, metadataService) {
    $scope.form = {};
    $scope.form.formActionAttr = $sce.trustAsResourceUrl('some.url');
    $scope.form.input1 = 'input1';
    $scope.form.input2 = 'input2';

    $scope.submitForm = function() {
        document.getElementById('appForm').submit();
    };
    $timeout(function() { $scope.submitForm() });
}

Upvotes: 2

Related Questions