使用Express为AngularJS渲染.ejs模板并使用AngularJS $ scope内的数据

时间:2015-06-11 09:59:25

标签: angularjs express mongoose ejs

我希望我可以用我在Stack Overflow上发布的第一个问题来解释自己。

我正在使用MEAN堆栈构建一个小型测试应用程序。

应用程序根据我创建的Express Route从Mongoose接收可变数据。

例如,网址为: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
    }
    });
};

../模型/ 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',
    }
]

我希望这些文件可以帮助解释我的问题。

提前感谢您帮助我

1 个答案:

答案 0 :(得分:0)

我找到了办法......

我的代码的以下更改修复了我的问题。

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功能: - )

希望我可以帮助其他人...最终这是一个简单的解决方案,也许有人在那里知道更好的方法。对我而言,它现在有效。