2017-04-12 35 views
0

控制器我建立一个网上商店网站看起来是这样的: enter image description here发送参数在angularjs

我加载的所有产品,当我将鼠标悬停在产品名称我看到产品的ID设置为动态URL

enter image description here

到目前为止,问题在于我对产品详细信息页面进行了硬编码。

我想知道的是我怎么能传递一个参数到控制器,所以我可以根据产品的ID加载该页面:

app.factory("shopFactory", function ($resource) { 
    return { 
     User: $resource("http://localhost:58495/users/api/User/?id=:id", { id: "@id" }), 
     Category: $resource("http://localhost:58495/category/api/categories"), 
     Product: $resource("http://localhost:58495/products/api/Products?from=:from&to=:to", { from: "@from", to: "@to" }), 
     ProductDetail: $resource("http://localhost:58495/products/api/Products?id=:id", { id: "@id" }), 
     Test: $resource("https://jsonplaceholder.typicode.com/users/:id", {id:"@id"}) 
    }; 

}); 

我厂的样子,我的产品控制器:

app.controller("productCtrl", function ($scope, shopFactory) { 
    var test = shopFactory.ProductDetail.get({ id: 1 }).$promise.then(function (response) { 
     CODE HERE 
    }); 
}); 

我也不怎么,但我想发送到控制器的参数是我希望看到的产品的ID,该控制器接收ID作为参数,并在这里插入:

var test = shopFactory.ProductDetail.get({ id: **hardCoded Part** }).$promise.then(function (response) { 
     CODE HERE 
    }); 

然后我加载所有基于我收到的参数的信息。
任何想法如何做到这一点?这种方法是正确的吗?或者我该怎么做?
感谢

+0

你的HTML在哪里?这是ID硬编码的地方吗? –

+0

@RaniRadcliff硬编码部分是id,我把1作为productId –

+0

目前有多少工作?当您单击超链接时,视图会更改并显示正确的内容? –

回答

0

好,说不上多么但我一直在寻找的是: $ routeProvider,我解决了我的问题

var test = shopFactory.ProductDetail.get({ id: $routeParams.producId }).$promise.then(function (response) { 
    CODE HERE 
}); 

基本上我得到了id参数f rom的URL,并加载插入它的ID,这是我想要的,一个非常好的文章解释它:https://namitamalik.github.io/routeParams-in-AngularJS/

0

我认为你正在试图做的是这样的:

<a ng-click="productCtrl.showDetails(product.id)>{{product.name}}</a> 

然后在控制器

$scope.showDetails = function(productId) { 
    shopFactory.ProductDetail.get({ id: productId }).$promise.then(function 
     (response) { 
     CODE HERE 
    }); 
} 
+0

谢谢,但我找到了另一种方式,我认为这是正确的方式,如果我没有找到它,我会使用你的。 –