【问题标题】:Unable to send data from controller to component无法将数据从控制器发送到组件
【发布时间】:2017-07-07 08:04:30
【问题描述】:

我有想在 html 代码中配置组件的情况。我有以下结构。

game.html 在 url 中提供,如 example.com/game/7999 应该显示游戏 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.js,似乎可以正常工作,因为game_id 显示正确。

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 的组件。这是score-info.component.js,其中game_id 不可见。

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。

【问题讨论】:

标签: angularjs angular-controller angular-components


【解决方案1】:

我将自己回答这个问题。答案由 JB Nizet 在 cmets 中提供。

第一个问题是命名相关的。代码需要遵守 angular.js 的命名约定,使用gameId: '&lt;'&lt;score-info game-id="game_id"&gt;

另外&lt; 绑定必须在没有花括号的元素中有引用:&lt;score-info game-id="game_id"&gt;

最后,组件控制器需要考虑 angular 1.5 -branch 和 1.6 -branch 之间的重大变化。见角度CHANGELOG。具体ScoreInfoController变成了

function ScoreInfoController(dataAccess) {
        self = this;
        self.$onInit = function() {
            dataAccess.game(self.game_id).then(function(game) {
                self.game = game;
            })
        }

【讨论】:

    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2019-11-29
    • 2016-10-04
    • 2021-04-07
    相关资源
    最近更新 更多