我有这样的情况,我想在html代码中配置组件。我有以下结构。
在example.com/game/7999这样的url中使用的game.html,它应该显示游戏7999的页面。
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<base href="/">
<title>Providence</title>
<script src="/js/angular.js"></script>
<script src="/data-access/data-access.module.js"></script>
<script src="/data-access/data-access.service.js"></script>
<script src="/score-info/score-info.module.js"></script>
<script src="/score-info/score-info.component.js"></script>
<script src="/js/game.js"></script>
</head>
<body>
<div ng-controller="myController">
<p> {{ game_id }} </p>
<score-info game_id="{{ game_id }}"></score-info>
</div>
</body>当game_id正确显示时,相应的game.js似乎可以正常工作。
angular.module('myApp', [
'dataAccess',
'scoreInfo' ],
function($locationProvider){
$locationProvider.html5Mode(true);
});
angular.
module('myApp').
controller('myController', function($scope, $location) {
var split_res = $location.path().split('/');
var game_id = split_res[split_res.length-1];
$scope.game_id = game_id
});我的问题出在组件上,我无法注入game_id。这里是game_id不可见的score-info.component.js。
angular.
module('scoreInfo').
component('scoreInfo', {
templateUrl : '/score-info/score-info.template.html',
controller : function ScoreInfoController(dataAccess) {
self = this;
console.log(self.game_id) // self.game_id == undefined
dataAccess.game(self.game_id).then(function(game) {
self.game = game;
});
},
bindings : {
game_id : '<'
}
});我注意到一些早期的答案建议使用连接控制器和组件的单独服务。这对我不起作用,因为我需要能够在一个页面中包含不同数量的scoreInfo -blocks。
发布于 2017-02-18 05:24:04
我要亲自回答这个问题。答案由JB Nizet在评论中提供。
第一个问题是与命名相关的。代码需要遵循angular.js的命名约定,并使用gameId: '<'和<score-info game-id="game_id">
此外,<绑定必须在不带大括号的元素中具有引用:<score-info game-id="game_id">
最后,组件控制器需要考虑angular 1.5 -branch和1.6 -branch之间的突破性变化。请参见angular CHANGELOG。具体来说,ScoreInfoController变成了
function ScoreInfoController(dataAccess) {
self = this;
self.$onInit = function() {
dataAccess.game(self.game_id).then(function(game) {
self.game = game;
})
}https://stackoverflow.com/questions/42303973
复制相似问题