我有一个MEAN堆栈,我用db-repeat循环数据库中的项目,{{items.value}}填充一些div上的文本。每个div都有ng-click="getItem(item._id)"
来触发角度页面重定向到
// dynamic pages for each ITEM, on ng-click
// from $routeParams.itemID in Ctrl
.when('/:itemID', {
templateUrl: 'views/item.html',
controller: 'ItemElementsController'
})
创建,Retreiving All和Deleting工作很棒.. Retreiving One正在响应[object Object],因此localhost:8080 / undefined和角度绑定{{items.value}}未填充
app.get('/api/items/:item_id', function(req, res) {
// use mongoose to get the one emotion from the database
Item.findById({
_id : req.params.item_id
},
function(err, item) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
res.json({ error: err });
} else {
res.json(item); // return the item in JSON format
}
});
});
在ItemElementsController中:
angular.module('ItemElementsCtrl', [])
// inject the Item service.factory into our controller
.controller('ItemElementsController', function($scope, $routeParams, $location, $http, ItemElements, isEmptyObjectFilter) {
// GET by ID ==================================================================
// get an Item after clicking it
$scope.getItem = function(id) {
ItemElements.getOne(id)
// if successful getByID, call our function to get the Item data
.success(function(data) {
// assign our Item
$scope.item = data;
// for use with a parameter in appRoutes.js using itemID as the variable
$scope.itemID = $routeParams.itemID;
// redirect
$location.path('/' + $routeParams.itemID);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
});
以及ItemElementsService:
angular.module('ItemElementsService', [])
// super simple service
// each function returns a promise object
.factory('ItemElements', function($http) {
return {
getOne : function(id) {
return $http.get('/api/items/' + id);
}
}
});
答案 0 :(得分:1)
$ routeParams.itemID目前还没有itemID参数。当您的路线为' /:itemId'时,它将填充数据。但现在你在' / list'或类似的东西(我看不到你所有的路线)。
.controller('ItemElementsController', function($scope, $routeParams, $location, $http, ItemElements, isEmptyObjectFilter) {
if ($routeParams.itemID !== undefinned){
ItemElements.getOne($routeParams.itemID)
// if successful getByID, call our function to get the Item data
.success(function(data) {
// assign our Item
$scope.item = data;
// for use with a parameter in appRoutes.js using itemID as the variable
$scope.itemID = $routeParams.itemID;
})
.error(function(data) {
console.log('Error: ' + data);
});
}
// GET by ID ==================================================================
// get an Item after clicking it
$scope.getItem = function(id) {
$location.path('/' + id);
};