AngularJS:如何在select事件中更改$ http.get中的url

时间:2015-04-27 07:23:55

标签: javascript php json angularjs

我有customers.php文件,它生成json数据。当我们像这样更改URL中的变量时,json数据列表正在发生变化

customers.php?var=5

在AngularJS中,我制作了两个独立部分的html文件。第一部分是具有特定值的选择选项。第2部分是显示json数据的部分。很明显第二部分使用 $ http.get(url),其中url在控制器中是 customers.php?var = selected_number

当用户在<中选择特定选项时,如何更改使用$ http.get的控制器中的网址?选择> ......< / select> html文件。

脚注:这是控制器文件的示例

var Pajsije = angular.module('CodeOverflow', ['ngRoute']);

    Pajsije.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/viewa', {
            templateUrl : 'viewa.html',
            controller  : 'ViewAController'
        })

        // route for the about page
        .when('/viewb', {
            templateUrl : 'viewb.html',
            controller  : 'ViewBController'
        })

        // route for the contact page
        .when('/viewc', {
            templateUrl : 'viewc.html',
            controller  : 'ViewCController'
        })
        .otherwise({
                redirectTo: '/viewa'
        });
});

// create the controller and inject Angular's $scope
Pajsije.controller('ViewAController', function($scope) {
    // create a message to display in our view
    $scope.message = 'Good look!';
});

Pajsije.controller('ViewBController', function($scope) {
    $scope.message = 'Look about page.';
});

Pajsije.controller('ViewCController', ['$scope','$http', '$templateCache', function($scope, $http, $templateCache) {

    $scope.myChange = function() {

    $http({method: 'GET', url: '../json-data/customers.php?idstudm=12', cache: $templateCache}).success(function (response) {$scope.names = response.records;});

};

}]);

3 个答案:

答案 0 :(得分:1)

我读了你的问题。我认为你有分离文件的问题。我猜,因为您使用的是AngularJS,所以您使用angular-route进行自动路由。所以,出于这个原因,你可能正在使用像main.html这样的文件,其中包括带有路由管理的customers.html。 如果在该文件中您具有在路由发生时将显示数据的机制,则当用户单击要选择的特定数据时,数据将不会在ng-controller中显示在主文件中。 (并非所有数据,只有myChange函数中的数据)

最好的问候。

答案 1 :(得分:0)

尝试$ rootScope,只要在UI(HTML页面)中进行选择(querypart),就可以在控制器中设置URL的变量部分。

$rootScope.variableURL = "customers.php?var=" + $scope.selected_number;
在发送$ http请求时将此附加到URL。如果我没有正确理解要求,请通知我。
我们已经知道$ rootScope可以在所有控制器上访问,并且可以用于跨越控制器和服务的较小数据。

答案 2 :(得分:0)

使用应使用ngModel指令将selectbox绑定到作用域模型,并在控制器中使用此模型。像这样:

<select ng-model="number" ng-change="myChange()">
    <option value="3">3</option>
    <option value="3">10</option>
</select>

控制器:

Pajsije.controller('ViewCController', ['$scope', '$http', '$templateCache', function ($scope, $http, $templateCache) {

    $scope.myChange = function () {
        $http({
            method: 'GET',
            url: '../json-data/customers.php?idstudm=' + $scope.number,
            cache: $templateCache
        }).success(function (response) {
            $scope.names = response.records;
        });
    };

}]);