【发布时间】:2015-08-26 22:58:48
【问题描述】:
我希望我可以用我在 Stack Overflow 上发布的第一个问题来解释自己。
我正在使用 MEAN 堆栈构建一个小型测试应用程序。
应用程序根据我创建的 Express Route 从 Mongoose 接收可变数据。
例如 url 是:localhost:3000/cities/test/Paris
根据城市名称,回复会给出城市名称和描述。我知道如何在 .ejs 模板中获取这些数据 但这不是我想要的。我想在 ngRepeat 中使用这些数据。
也许这不是正确的方法,但也许你可以帮我解决这个问题。
我想要这样做的原因是因为我不想要一个单页应用程序,而是一个可以为每个城市反复使用的 Angular 模板,并且只使用从 mongoose find() 结果返回的数据而不是整个城市数组。
app.js:
var cityRoutes = require('./routes/cities');
app.use('/cities', cityRoutes);
app.set('views', './views'); // specify the views directory
app.set('view engine', 'ejs'); // register the template engine
./routes/cities/cities.js :
var express = require('express');
var citiesList = require('../server/controllers/cities-controller');
var bodyParser = require('body-parser');
var urlencode = bodyParser.urlencoded({ extended: false });
var router = express.Router();
// because this file is a fallback for the route /cities inside app.js
// the route will become localhost:3000/cities/test/:name
// not to be confused by its name in this file.
router.route('/test/:name')
.get(citiesList.viewTest)
module.exports = router;
../server/controllers/cities-controller.js :
var City = require('../models/cities');
module.exports.viewTest = function(request, responce){
City.find({ stad: request.params.name }, function(err, results){
if (err) return console.error(err);
if (!results.length) {
responce.json( "404" );
} else {
responce.render('angular.ejs', { messages:results });
// through this point everything works fine
// the angular.ejs template gets rendered correctly
// Now my problem is how tho get the results from the
// response.render inside the Angular directive
// so I can use the data in a $scope
}
});
};
../models/cities.js
var mongoose = require('mongoose');
module.exports = mongoose.model('City', {
stad: { type: String, required: true },
omschrijving: String
});
AngularJS 指令:
// This is where I would like to use the messages result data
// so I can create a $scope that handles data that can be different
// for each url
// so basically I am using this directive as a template
app.directive('bestelFormulier', function () {
return {
restrict: 'E',
templateUrl: '/partials/bestel-formulier.html',
controller: ['$scope', '$http', '$resource', '$cookieStore',
function($scope, $http, $resource, $cookieStore){
// at this point it would be nice that the $scope gets the
// url based results. But I don't now how to do that..
// at this point the var "Cities" gets the REST API with
// all the cities...
var Cities = $resource('/cities');
// get cities from mongodb
Cities.query(function(results){
$scope.cities = results;
//console.log($scope.products);
});
$scope.cities = {};
}],
controllerAs: 'productsCtrl'
}
});
数据库是这样存储的:
[
{
stad: 'Paris',
omschrijving: 'description Paris',
},
{
stad: 'Amsterdam',
omschrijving: 'description Amsterdam',
}
]
我希望包含的这些文件有助于解释我的问题。
提前感谢您帮助我
【问题讨论】:
标签: angularjs express mongoose ejs