I am trying to grab the identifier of a product out of the url (eg. /product/<productId>
), grab the Product object out of mongodb and make that object accessible in the $scope
of my application. Grabbing the productId out of the url works fine with $routeParams
, but I am having a hard time getting the object out of the mongodb and into the scope.
My guess is that I need to add code in the products-controller.js
on the server side, but how can I call the productId from the $scope on the server side?
I know what the query should look like (eg. db.products.find({_id : ObjectId("5422c8b2d4cc50e99f007f73")})
)
server.js
app.get('/api/products', productsController.list);
app.js
var app = angular.module('productApp', ['ngResource', 'ngRoute']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '/views/productsoverview.html',
controller: 'productsController'
})
.when('/product/:productId', {
templateUrl: '/views/productFocus.html',
controller: 'productFocusController'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true)
}]);
app.controller('productsController', ['$scope', '$resource',
function($scope, $resource) {
var Product = $resource('/api/products');
$scope.products = [];
Product.query(function (results) {
$scope.products = results;
});
}]);
app.controller('productFocusController', ['$routeParams', '$scope', '$resource',
function($routeParams, $scope, $resource) {
if($routeParams.productId) {
$scope.productId = $routeParams.productId
}
}]);
products-controller.js (server)
var Product = require('../models/product');
module.exports.list = function (req, res) {
Product.find({}, function (err, results) {
res.json(results);
});
}