gpt4 book ai didi

javascript - 如何以 Angular $http 传递 URL 参数

转载 作者:行者123 更新时间:2023-11-30 12:55:17 25 4
gpt4 key购买 nike

我正在将服务器端 CRUD 应用程序转换为 Angular.js,但遇到一个小问题。

我正在使用 $http 获取数据并通过 ng-repeat 显示所有数据。我想让用户能够单击特定项目并将他们重定向到资源。

那么如何将 URL 参数动态传递给 $http get 调用?

这是我如何建立资源链接 (car.id = 3)

<a ng-href="/#/cars/{{car.id}}">Edit</a>

链接应该转到 http://local.dev/#/cars/3

那么如何在我的 Controller 中绑定(bind)动态 url?

这是我的 Controller 的精简版

App.controller('CarIndexCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {

$scope.car = {};

$http({
method: 'GET',
url: $location.$$url,
})
.success(function (data, status, headers, config) {
$scope.car = data;
})
.error(function (data, status, headers, config) {
// error
});

}]);

所以我有兴趣以 Angular 方式绑定(bind) URL。上面的解决方案有效,但感觉很像 hack。我对 Angular 不是很熟悉,所以我现在喜欢使用默认值。不过我以后可能会考虑 restangular 或 ng-resource...

最佳答案

the above solution works, but feels very much like a hack.

我不认为它是 hack 或什么乱七八糟的东西。

我会在 Controller 中生成 URL 列表(从我的 Angular 来看,它更利于代码维护)而不附加到 HTML 中。像这样的东西:

 $scope.urlList = [];

$http({
method: 'GET',
url: $location.$url,
})
.success(function (data, status, headers, config) {
$scope.car = data;
$scope.urlList.push("/#/cars/" + data.id);
})
.error(function (data, status, headers, config) {
// error
});

在 HTML 中:

<li ng-repeat="url in urlList" repeat-done="layoutDone()" ng-cloak>
<a ng-href="{{url}}">Edit</a>
</li>

顺便说一句,我建议您使用一些加载程序,因为我们从 promise(也称为异步)生成的 URL 链接因此有延迟。

演示 Fiddle

关于javascript - 如何以 Angular $http 传递 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19379264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com