【发布时间】:2014-05-20 11:18:43
【问题描述】:
我有一个 MEAN 堆栈,我在其中使用 ng-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'
})
创建、检索全部和删除效果很好。但检索一个是用 [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);
}
}
});
【问题讨论】:
标签: json node.js angularjs express mongoose