【问题标题】:Using Express to render an .ejs template for AngularJS and use the data inside AngularJS $scope使用 Express 为 AngularJS 渲染一个 .ejs 模板并使用 AngularJS $scope 中的数据
【发布时间】: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


    【解决方案1】:

    我想出了一个办法……

    对我的代码的以下更改解决了我的问题。

    在 app.js 中

    var cityRoutes = require('./routes/cities');
    app.use('/', cityRoutes);
    // removed the name cities
    

    ./routes/cities/cities.js :

    router.route('/cities/test/:name')
    
        .get(citiesList.viewTest)
    
    // added this route to use as an API
    router.route('/api/cities/test/:name')
    
        .get(citiesList.viewStad)
    

    ../server/controllers/cities-controller.js :

    // added this callback so that a request to this url
    // only responses with the data I need
    module.exports.viewStad = 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.json( results );
            }
        });
    };
    

    在我的 AngularJS 应用程序中,我添加了 $locationDirective 并将 Angular 指令中的以下内容更改为:

    var url = $location.url();
    var Cities = $resource('/api' + url);
    // now when my .ejs template gets loaded the Angular part looks at
    // the current url puts /api in front of it and uses it to get the
    // correct resource
    

    这就是我可以在我的 $scope 中使用它并使用所有可爱的 Angular 功能的方式:-)

    希望我可以帮助其他人...最终这是一个简单的解决方案,也许有人知道更好的方法来做到这一点。对我来说,它现在可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2015-07-17
      • 2023-03-10
      • 2014-01-31
      • 2019-11-19
      • 2012-05-08
      相关资源
      最近更新 更多