从角度控制器

时间:2016-04-17 15:04:10

标签: angularjs

以下是我的$ routeProvider.when

.when("/products/:id",{
        templateUrl:"app/views/product.html",
        controller:"productController"
    })

我想在产品控制器中访问:id的值。

基于此我将填充产品详细信息。

网址为 /index.html#/products/3

4 个答案:

答案 0 :(得分:2)

$routeParams注入控制器工厂功能。

.controller('MainController', function($scope, $routeParams) {
     $scope.id= $routeParams.id;
})

答案 1 :(得分:2)

您可以使用$routeParams

在控制器中访问它
app.controller('productController', function ($scope, $routeParams) {
  $scope.productId = $routeParams.id;
};

了解更多here

$stateParams适用于自定义ui-router

答案 2 :(得分:2)

您可以在控制器中使用$routeParams.id

答案 3 :(得分:1)

使用$ location服务

要访问路径的任何部分,您需要使用$ location服务。它允许您使用网址的不同部分。例如(来自文档)

// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var url = $location.url();
// => "/some/path?foo=bar&baz=xoxo"

但你想要的是这个

// given url http://example.com/#/some/path?foo=bar&baz=xoxo
var path = $location.path();
// => "/some/path"

这将返回一个字符串,它是#

之后的所有内容

所以你可以使用slice或其他一些JS函数来获得你需要的部分。

祝你好运

相关问题