问题描述
我想弄清楚如何将ID传递到我的 PlayerDetailController
,然后在我的服务中使用它。
I am trying to figure out how to pass an Id into my PlayerDetailController
and then use it in my service.
我在下面的路由我的主要 app.js
:
I have the following route in my main app.js
:
var players = require('./routes/players');
app.use('/players', players);
和我有以下路线中的玩家
路线(路由/ players.js
)
And I have the following routes inside of the players
route (routes/players.js
):
var express = require('express');
var router = express.Router();
/* GET /players listing. */
router.get('/', function(req, res, next) {
res.render('players', { title: 'Players', action: 'list'});
});
/* GET /player details. */
router.get('/:id', function(req, res, next) {
res.render('players', { title: 'Player Details', action: 'details'});
});
module.exports = router;
在我的主 players.ejs
模板如下:
<!-- other layout elements -->
<% if (action === 'details') { %>
<% include partials/players/details %>
<% } else if (action === 'update') { %>
<% include partials/players/update %>
<% } else if (action === 'remove') { %>
<% include partials/players/remove %>
<% } else { %>
<% include partials/players/list %>
<% } %>
<!-- other layout elements -->
和我的 deatils.ejs
部分:
<div ng-controller="PlayerDetailsController">
<div class="playerDetails">
<p>
<strong>{{ player.name}} - {{ player.position }} - {{ player.team }}</strong><br/>
Touchdowns: {{ player.touchdowns }}<br/>
Yards: {{ player.yards }}
</p>
</div>
</div>
和我PlayerDetiails服务:
And my PlayerDetiails service:
// PlayerDetails Service
app.factory('PlayerDetails', ['$http', function($http){
// below is where I'm trying to inject the Id
return $http.get('/api/player/:id');
}]);
但我不知道我怎么可以通过在我的路线中显示的ID(例如的http://本地主机:3000 /播放/ 550130d32f3345bc065f2ecf
)到我控制器使我的控制器调用并接收正确的玩家数据。我会怎么做呢?我以为我可以一个 ID
属性添加到 res.render
的电话,但我不知道我会用它做在EJS模板。任何帮助将大大AP preciated!
But I have no idea how I can pass the Id that shows up in my route (ex. http://localhost:3000/players/550130d32f3345bc065f2ecf
) into my controller so that my controller calls and receives the correct player data. How would I do this? I thought I could add a id
property to the res.render
call, but I'm not sure what I would do with it in the EJS template. Any help would be greatly appreciated!
推荐答案
通过ID到您的模板:
router.get('/:id', function(req, res, next) {
res.render('players', { title: 'Player Details', action: 'details', id: req.params.id});
});
NG-init接收到的ID:
ng-init receives the id:
<div ng-controller="PlayerDetailsController" ng-init="id = <%= id %>">
PlayerDetails服务:
PlayerDetails service:
app.service('PlayerDetails', ['$http', function($http){
return {
get: function(id) {
return $http({
url: '/api/player/:id',
params: {id: id},
method: 'GET'
});
}
};
}]);
在某处PlayerDetailsController:
Somewhere in PlayerDetailsController:
// id is from ng-init
PlayerDetails.get($scope.id).success(function(player) {
$scope.player = player;
}).error(function(error) {
console.error(error);
});
这篇关于获取ID为在EJS模板项目,并注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!