我有一個包含不同產品的主頁,我想在其他視圖中顯示一個選定的產品。 (詳細視圖)。顯示我使用ng-repeat的產品,它遍歷product-Array。從ng-repeat中獲取一個項目
現在,當點擊一個按鈕時,我會從ng-repeat中獲得單個產品。然後,視圖會隨着所選產品而變爲細節視圖。視圖的切換應該通過id,因爲這需要向我的API發出請求。
在此狀態下,我嘗試使用$ routeParams,但它並沒有工作。然後我在這裏搜索了stackoverflow。我讀過它可能是範圍問題,因爲我試圖將ID傳遞給控制器。 (我需要另一個控制器中的Id)。 當我點擊主頁上的按鈕時,沒有任何事情發生。
我希望,有人有一個想法,如何解決這個問題。
這裏是API的stample JSON文件:
{
"_id": "582ae2beda0fd7f858c109e7",
"title": "Lorem ipsum",
"smalldescription": "Lorem ipsum dolor sit amet,",
"longdescription": "Lorem ipsum dolor sit ametLorem ipsum ",
"price": "2500",
"img": "Imagetxt"
}
這裏是我的代碼:
app.js
angular.module('Productportfolio', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: '/components/home/home.html',
controller: 'ProductCtrl'
})
.when('/detail/:productId', {
templateUrl: '/components/detail/detail.html',
controller: 'DetailCtrl'
.otherwise({redirectTo: '/home'});
}]);
home.html的
<div ng-controller="ProductCtrl as ProductCtrl">
<div ng-repeat="product in ProductCtrl.products ">
<h3>{{product.title}}</h3>
<button ng-click="loadDetail(product)">Detailansicht</button>
</div>
</div>
個
ProductCtrl.js
angular.module('Productportfolio')
.controller('ProductCtrl', ['APIService','$location', function (APIService,$location) {
var vm = this;
vm.products = null;
init();
function init() {
APIService.getProducts()
.then(function (response) {
vm.products = response.data;
})
.catch(function (error) {
console.log("error at GET");
});
}
vm.loadDetail = function(product){
$location.path('/detail'+product.id);
}
}]);
APISvc.js
angular.module('Productportfolio')
.service('APIService', ['$http', function ($http) {
var svc = this;
svc.root = 'http://localhost:3000/api';
svc.API = {
'getProducts': getProducts,
'getProduct' : getProduct
};
return svc.API;
function getProducts() {
return $http({
method: 'GET',
url: svc.root + '/products'
})
}
function getProduct(id){
return $http({
method: 'GET',
url : svc.root +'/product/'+id
})
}
}]);
DetailCtrl.js
angular.module('Productportfolio')
.controller('DetailCtrl', ['APIService', '$routeParams', function (APIService, $routeParams) {
var vm = this;
vm.product = null;
vm.productId = $routeParams.productId;
init();
function init() {
APIService.getProduct(vm.productId)
.then(function (response) {
console.log(response);
vm.product = response.data;
})
.catch(function (error) {
console.log("error at GET");
});
}
}]);
檢查vm.loadDe中的路徑tail()函數。我認爲它是$ location.path('/ detail /'+ product.id); – neelima
年,你是對的。我改變了它,點擊按鈕時沒有任何反應。我不知道這種方法是否正確地通過ng-click來提交產品 –
您可以嘗試從div中刪除ng控制器嗎? –