如何$ http.post与数据中的有效负载?

时间:2014-07-15 02:47:22

标签: angularjs angularjs-scope angularjs-service angularjs-controller angularjs-http

如何从AngularJS中的表单发布数据?

<form data-ng-submit="doSomething()">
    <input type="text" data-ng-input="do_obj.text"/>
    <input type="email" data-ng-input="do_obj.email"/>
    <input type="submit" value="Do something"/>
</form>
$scope.doSomething = function () {
        $http({url: '/api/oauth2/register', method: 'POST', data: $scope.do_obj}
        ).then(function (data, status, headers, config) {
                   $log.info("data = ", data, "status = ", status,
                             "headers = ", headers, "config = ", config);
               }
        );
};

Plnkr (bootstrap styled)

1 个答案:

答案 0 :(得分:0)

请参阅plunker代码here

将data-ng-input更改为data-ng-model并更新data-ng-submit以将模型传递到范围控制器进行处理。

HTML:

<body data-ng-app>
        <div data-ng-controller="DoCtrl" class="container" style="margin: 15px">
            <form data-ng-submit="doSomething(do_obj)" role="form" class="form-inline">
                <div class="form-group">
                    <input type="text" data-ng-model="do_obj.bar"
                           placeholder="Enter text"
                    />
                </div>
                <div class="form-group">
                    <input class="form-group" type="email"
                           data-ng-model="do_obj.email"
                           placeholder="Enter email"
                    />
                </div>
                <div class="form-group">
                    <input class="btn btn-lg" type="submit"
                           data-ng-class="{'btn-info': hover}"
                           data-ng-mouseenter="hover = true"
                           data-ng-mouseleave="hover = false"
                           value="Do something"
                            />
                </div>
            </form>
        </div>
    </body>

发布的语法是$ http.post({url},{payload});.我已更新您的控制器功能以接收参数以传递到帖子。

控制器代码:

function DoCtrl($scope, $http, $log) {
    $log.info("In DoCtrl");
    $scope.do_obj = {};
    $scope.doSomething = function (data) {
      $http.post('/api/oauth2/register', data)
        .success(function(successData){
          console.log(successData);
        });
    }
}