如何使用ngRoute将产品名称与ID参数传入URL路径
嗨,这事儿不难,我给你一步步拆解实现方案:
1. 先把产品名称转成URL友好的格式(Slug)
产品名称里可能有空格、特殊字符,直接丢URL里会出问题,所以先写个小函数把它转成符合URL规范的字符串:
$scope.formatProductSlug = function(productName) { return productName.toLowerCase() .replace(/[^a-z0-9]/g, '_') // 把所有非字母数字的字符换成下划线 .replace(/_+/g, '_'); // 把连续的下划线合并成一个,避免冗余 };
2. 修改跳转函数,拼接成你要的URL格式
原来的代码是用search传id参数,现在我们直接把格式化后的名称和id拼接成路径:
$scope.watchDetail = function() { const formattedName = $scope.formatProductSlug($scope.nameProduct); const productId = $scope.seeMore.Id; // 拼接成 /the_name_of_product_id 这样的路径 $location.path(`/${formattedName}_${productId}`); };
3. 配置AngularJS路由,匹配新的URL格式
你需要在路由配置里添加对应的规则,让Angular能识别这个路径并加载详情页:
angular.module('yourApp', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider // 匹配 /xxx_xxx 这样的路径,把整个路径作为productSlug参数 .when('/:productSlug', { templateUrl: 'product-detail.html', controller: 'ProductDetailController' }) // 首页路由保持不变 .when('/', { templateUrl: 'home.html', controller: 'HomeController' }); }]);
4. 在详情页获取并解析参数(别再用原生的URL解析了!)
AngularJS提供了$routeParams服务,能直接获取路由参数,比你自己写getUrlVars靠谱多了:
angular.module('yourApp') .controller('ProductDetailController', ['$scope', '$routeParams', function($scope, $routeParams) { // 拆分slug,下划线最后面的部分就是id const slugParts = $routeParams.productSlug.split('_'); const productId = slugParts.pop(); // 剩下的部分拼接回产品名称(如果需要还原空格的话,把下划线换回空格) const productName = slugParts.join('_').replace(/_/g, ' '); // 现在你就拿到了产品名称和ID,可以去调用API获取详情啦 console.log('产品ID:', productId); console.log('产品名称:', productName); }]);
额外小提示
如果产品名称本身就包含下划线,拆分的时候要注意——不过上面的代码已经考虑到了,用pop()取最后一个下划线后面的内容作为ID,剩下的拼接回名称,不会有问题。
另外,如果你觉得/the_name_of_product_id这种格式可读性一般,也可以改成更清晰的/product/:productName/:productId(比如/product/the_name_of_product/123),这种格式解析起来更简单,只需要在路由里定义/product/:productName/:productId,然后直接从$routeParams.productName和$routeParams.productId取值就行。
内容的提问来源于stack exchange,提问作者Chuck Villavicencio
相关产品推荐
相关产品推荐

