【问题标题】:Pass form data to laravel controller using AngularJS使用 AngularJS 将表单数据传递给 laravel 控制器
【发布时间】:2015-12-24 02:42:57
【问题描述】:

我在这里有一个简单的代码,想将数据传递给 laravel 控制器,以便将其存储到数据库中。我的代码是:

AccountController.php

public function store(Request $request)
    {
        Account::create(array(
            'email' => $request->get('email'),
            'name' => $request->get('text'),
            'age' => $request->get('age'),
        ));

        return ['success' => true];
    }

刀片

<form ng-submit="newAccount()">
          <div class="form-group">
            <label for="email">Email address</label>
            <input type="email" class="form-control" id="email" ng-model="accountData.email">
          </div>

          <div class="form-group">
            <label for="fullname">Full Name</label>
            <input type="email" class="form-control" id="fullname" ng-model="accountData.name">
          </div>

          <div class="form-group">
            <label for="age">age</label>
            <input type="email" class="form-control" id="age" ng-model="accountData.age">
          </div>
</form>

app.js

var app = angular.module('accountsApp', []);

app.controller('accountsCtrl', function($scope, $http) {

 $scope.newAccount = function() {
      //add data
      $http.post('/api/accounts', 
      {
        //what will I put here to get the textbox values?
      }).
      .success(function(response) {
        scope.accounts = response;
      })
      .error(function(response) {
        console.log(response);
      });

    };

});

正如您在我的app.js 中看到的那样,我一直不知道如何从刀片中的文本框中获取数据。是否有捷径可寻?谢谢。

【问题讨论】:

  • 为什么你不用jquery来做这么简单的事情呢?您想通过 ajax 或通过提交表单操作将其发送到控制器
  • 因为我想学习 Angular @patricio

标签: php angularjs laravel


【解决方案1】:

很简单,你可以添加一个对象来传递 POST 请求。 Laravel 会以 1 比 1 的比例选择这些变量。

var app = angular.module('accountsApp', []);

app.controller('accountsCtrl', function($scope, $http) {

 $scope.newAccount = function() {
      //add data
      $http.post('/api/accounts', 
      {
        email: $scope.accountData.email,
        text: $scope.accountData.text,
        age: $scope.accountData.age

      }).
      .success(function(response) {
        scope.accounts = response;
      })
      .error(function(response) {
        console.log(response);
      });

    };

});

【讨论】:

  • 那么你可能有另一个可能,也许你遇到了 Laravel 的批量赋值异常。检查控制台中的网络选项卡发生了什么。
  • 我现在看到了问题,$scope.accountData.email 没有这样做。它一定是什么。我尝试了一个静态值,它可以工作。例如电子邮件:'test'
  • @FewFlyBy 抱歉回复晚了,我知道你做错了什么,所有的表单类型都是&lt;input type="email" 这应该是type="text" 否则它不会验证并且不会发送!
猜你喜欢
  • 2019-01-06
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
相关资源
最近更新 更多