如何使用AngularJS保存输入值

时间:2016-05-31 08:59:35

标签: javascript java html angularjs

我正在开发一个网站,其中包含一个名为评论的字段,其中某些特定用户可以发布这些评论。 我的HTML代码:



<form>
  <input ng-model="stack"></input>
  <button ng-click="save()">Save</button>
  <p>Your comment:  <span ng-bind="stack"></span></p>
</form>
&#13;
&#13;
&#13;

注释应保存到变量中,然后发布在我的Web服务中,这是一个json文件,因此我可以进行数据库调用。我必须使用$ http.post 我正在使用AngularJS,我使用java(JAXB)编写了我的webservice。

&#13;
&#13;
//Controller:
$scope.save = function() { 
  alert(name); 
} 
//In save I put alert to test because all the functions save I tested hadn't done what I need. 
//server 
$http({ 
  method: 'POST', 
  url: 'url', 
  data: "stack=" 
});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

$http.post为你做到了。

这是html代码:

&#13;
&#13;
<form ng-submit="save()">
      <input ng-model="stack"></input>
      <button type="submit">Save</button>
      <p>Your comment:<span ng-bind="stack"></span></p>
</form>
&#13;
&#13;
&#13; 这是控制器功能:

&#13;
&#13;
function myController($scope,$http){
        $scope.save=function(){
            
      var data=$scope.stack;  
       /* post to server*/
        $http.post(url, data)
            .then(
           function(response){
          // success callback
                 }, 
           function(response){
           // failure callback
               });
                               
             }
        }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$scope.save = function (data1) {
            var value = JSON.stringify(data1);
            $http({
                method: 'POST',
                cache: false,
                url: serviceBasePath + '/api/save',
                data: value,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                }
            }).success(function (data, status) {
                $('.modal-backdrop').remove();
                $scope.tableParams.reload();
                $scope.Form.$setPristine();
            }).error(function (data, status) {
                $scope.errors = [];
                $scope.errors.push(data);
            });
        };