如何将Laravel控制器功能与Angular View链接

时间:2016-04-25 07:27:18

标签: angularjs laravel angularjs-scope laravel-5.2

我正在开发一个laravel Web应用程序,最近我嵌入了angularjs来搜索数据库中的数据。但是现在我只是使用一个数组进行搜索。在我的AngularJs模块中,我将搜索功能指向$scope.url = 'Students@search';,但这对我不起作用。 我想知道如何告诉AngularJS $scope.url在我的控制器中指向此搜索功能,以便用户可以轻松搜索数据。 我在学生控制器中有搜索功能:

 public function search(){
            $data = file_get_contents("php://input");

            $objData = json_decode($data);

            // Static array for this demo
            $values = array('php', 'web', 'angularjs', 'js');

            // Check if the keywords are in our array
            if(in_array($objData->data, $values)) {
                echo 'I have found what you\'re looking for!';
            }
            else {
                echo 'Sorry, no match!';
            }
  }

MyApp.js文件:

function SearchCtrl($scope, $http) {
    $scope.url = 'Students@search'; // The url of our search

    // The function that will be executed on button click (ng-click="search()")
    $scope.search = function() {

        // Create the http post request
        // the data holds the keywords
        // The request is a JSON request.
        $http.post($scope.url, { "data" : $scope.keywords}).
        success(function(data, status) {
            $scope.status = status;
            $scope.data = data;
            $scope.result = data; // Show result from server in our <pre></pre> element
        })
        .
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;         
        });
    };
}

角度搜索视图:

<div ng-controller="SearchCtrl">
                                    <form class="well form-search">
                                        <label>Search:</label>
                                        <input type="text" ng-model="keywords" class="input-medium search-query" placeholder="Keywords...">
                                        <button type="submit" class="btn" ng-click="search()">Search</button>
                                        <p class="help-block">Try for example: "php" or "angularjs" or "asdfg"</p>      
                                    </form>
                                    <pre ng-model="result">
                                    @{{result}}
                                    </pre>
</div>

1 个答案:

答案 0 :(得分:0)

您可以先创建路线。例如 -

getApplicationContext()

然后您可以将其设置为

Route::get("/search", ["as" => "studentSearch", "uses" => "Students@search"]);

或者如果它不是刀片模板,那么您必须手动设置网址。像

 $scope.url = '{{ route ("studentSearch") }}';