【问题标题】:Angular directive binding isolated scope with ng-repeatAngular 指令绑定隔离范围与 ng-repeat
【发布时间】:2014-12-26 23:03:33
【问题描述】:

指令中 score_stats 的值始终未定义,并且在父作用域中,stats 变量具有正确的值。我做错了什么?

我在模板中有这段代码(并且 fixtures_stats 是一个数组):

div(ng-repeat="stats in fixture_stats")
  scenario-analysis(score_stats="stats")

指令中的这段代码:

{                                                                    
  templateUrl: '/' + appVersion + '/directives/scenario-analysis.html',                                                                                                                                              
  scope:{
      score_stats:'=score_stats'
  },
  controller: function($scope, $element, $attrs) {
      console.log('directive $scope.score_stats: ' + $scope.score_stats +
                  ', $scope.$parent.stats: ' + $scope.$parent.stats);
  },                                                                               
};

指令模板中的这段代码:

h3 Scenarios for {{ score_stats.score1 }}-{{ score_stats.score2 }} score combo

在控制台中我得到:

directive $scope.score_stats: undefined, $scope.$parent.stats: [object Object]
directive $scope.score_stats: undefined, $scope.$parent.stats: [object Object]

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    首先你应该为score_stats属性使用表达式:

    div(ng-repeat="stats in fixture_stats")
      scenario-analysis(score_stats="stats")
    

    然后在指令定义而不是scope_stats范围属性将变成驼峰式:

    scope: {
        scoreStats: '='
    }
    

    所以在指令模板中你需要改为:

    Scenarios for {{ scoreStats.score1 }}-{{ scoreStats.score2 }} score combo
    

    【讨论】:

    • 无变化:指令中仍未定义 score_stats
    • 范围属性名称中的_ 分隔符存在一些混淆。我建议使用常见的蛇形盒以获得可预测的结果。查看更新的答案。
    猜你喜欢
    • 2013-03-15
    • 2015-03-17
    • 2014-08-07
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2014-10-23
    相关资源
    最近更新 更多