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



我有客户.php文件生成json数据。当我们像这样更改 url 中的变量时,json 数据列表正在更改

customers.php?var=5

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

当用户

选择特定选项<选择>时,如何更改使用 $http.get 的控制器中的 url ...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;});
};
}]);
每当在

UI(HTML 页面)中进行选择(查询部分)时,尝试$rootScope在控制器中设置 URL 的变量部分。

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

Use 应该使用 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;
        });
    };
}]);

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

此致敬意。

最新更新