Reputation: 965
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);
});
}
Upvotes: 0
Views: 166
Reputation: 16066
how can I call the productId from the $scope on the server side? pass the $scope.productId as a parameter, include it in the url like
your route on the server side could be something like
/api/products/:productId
then pass the parameter you get from the client url to your resource:
pp.controller('productsController', ['$scope', '$resource', '$routeParams',
function($scope, $resource,$routeParams) {
var ProductEndpoint = $resource('/api/products/:productId',{productId:'@productId'});
var product = new ProductEndPoint();
product.productId = $routeParams.productId;
$scope.products = [];
Product.query(function (results) {
$scope.products = results;
});
}]);
on the server side:
var Product = require('../models/product');
module.exports.list = function (req, res) {
Product.find({_id:req.params.productId}, function (err, results) {
res.json(results);
});
}
Upvotes: 1