使用基于查询字符串参数的 Angular 填充选择元素

Fill select element using Angular based on query string parameter

本文关键字:参数 Angular 填充 元素 选择 字符串 于查询 查询      更新时间:2023-09-26

我需要用从 web api 检索的数据填充选择元素

我对 Web API 使用属性路由

api/project/{pid}/users

如果手动传递参数 pid 时,它工作正常。

我需要使用 angular $http.get() 通过查询字符串传递参数

我试过这个

this.getItems = function () {
   return $http({
        url: '/api/project/{pid}/users',
        method: 'GET',
        data: $.param({pid:123})
    });
}

在小提琴手中,我得到了 404 错误。

http://localhost/api/project/%7Bpid%7D/users

我读过关于 $location.$Search 和$routParam的信息,但我需要额外的帮助。

Angular 不会像在视图中那样解析字符串并替换 {pid},所以你可以简单地做:

this.getItems = function () {
   return $http({
        url: '/api/project/' + pid + '/users',
        method: 'GET'
    });
}

甚至更短:

this.getItems = function () {
   return $http.get('/api/project/' + pid + '/users');
}

当用户在选择元素中选择确切选项时,我需要调用控制器函数。

角度服务:

dataFactory.getUsers = function (pid) {
            return $http.get(urlBase + 'api/projects/project/' + pid +'/users');

角度控制器:

function getUsers(pid) {
                dataFactory.getUsers(pid)
                    .success(function (user) {
                        $scope.users = user;
                    })
                    .error(function (error) {
                        $scope.status = error.message;
                    });
            }'

.HTML:

<select ng-model="user" ng-options="item.id as item.name for item in users" ng-click="getUsers(pid)">

"手动传递pid"是什么意思?

我想知道你的html中有类似ng-click="getItems()"的东西。您可以将其更改为ng-click="getItems(pid)"并将其传递给您的函数

this.getItems = function (pid) {
   return $http.get('/api/project/' + pid + '/users');
}

params选项会将搜索对象添加到 url 的末尾,例如

?users=jondoe

更新

查看您的新代码,一切看起来都不错。但是在你的 HTML 中它应该是

<select ng-model="user" ng-options="item.id as item.name for item in users" ng-click="getUsers(item.id)">

此外,该函数应该是

$scope.getUsers(pid) {
                dataFactory.getUsers(pid)
                    .success(function (user) {
                        $scope.users = user;
                    })
                    .error(function (error) {
                        $scope.status = error.message;
                    });
            }'