如何从Angular发布到Slim?

时间:2016-01-16 19:25:57

标签: php angularjs post routing slim

我有以下代码,但它似乎不起作用。我试图寻找一个解决方案,但大多数都是较旧且非常具体的答案。

我达到了这一点:

  1. 模板通过配置在ng-view中加载。
  2. 表单会在点击时提交。
  3. 什么都没发生。
  4. 我使用网络中的Google控制台检查POST,但它不会触发。

    我错过了什么?我从this article获得了大部分代码。

    HTML查看,即表单

    <h2>Add new job</h2>
    <form novalidate name="AddNewForm" method="post" action="">
    
        <input type="text" class="form-control" ng-model="job.title" placeholder="Title" required />
        <input type="text" class="form-control" ng-model="job.company" placeholder="Company" required />
        <input type="text" class="form-control" ng-model="job.description" placeholder="Description" required />
        <input type="text" class="form-control" ng-model="job.location" placeholder="Location" required />
        <br/>
        <button ng-disabled="AddNewForm.$invalid || isUnchanged(job)" ng-click="add_new(job)" class="btn">Save!</button>
    
    </form>
    

    角度配置控制器

    (function() {
    
        angular
        .module('app')
        .config(function($routeProvider) {
            $routeProvider.when('/add-job', {
                templateUrl: 'templates/add-job.html',
                controller: AddController   
            });
        });
    
        function AddController($http, $location) {
            var that = this;
    
            that.master = {};
            that.activePath = null;
    
            that.add_new = function(job, AddNewForm) {
                $http.post('api/add_job', job).success(function () {
                    alert("added!");
                    that.reset();
                    that.activePath = $location.path('/');
                });
    
                that.reset = function () {
                    that.job = angular.copy(that.master);
                };
    
                that.reset();
            };
        }
    })();
    

    超薄API

    require 'vendor/autoload.php';
    
    $app = new \Slim\App; 
    
    $app->post('/add_job', 'addJob');
    
    $app->run();
    
    function addJob() {
        $request = Slim::getInstance()->request();
        $job = json_decode($request->getBody());
        $sql = "INSERT INTO jobs (title, company, description, location) VALUES (:title, :company, :description, :location)";
        try {
            $db = getConnection();
            $stmt = $db->prepare($sql);  
            $stmt->bindParam("title", $job->title);
            $stmt->bindParam("company", $job->company);
            $stmt->bindParam("description", $job->description);
            $stmt->bindParam("location", $job->location);
            $stmt->execute();
            $job->id = $db->lastInsertId();
            $db = null;
            echo json_encode($job); 
        } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
        }
    }
    

1 个答案:

答案 0 :(得分:1)

您在控制器中使用controllerAs语法,但在视图中使用$scope语法。 请注意,您链接到的文章在控制器中使用$scope来表示与当前视图设置匹配的所有变量

您需要选择其中一个,以便视图与控制器兼容