在嵌套指令方案中从内部指令(模板内部)传递属性



参考以下代码片段:

普伦克演示 1工作正常,我进行了以下更改:

.HTML

<!DOCTYPE html>
<html ng-app="MultiplicationApp">
  <head>
    <link rel="stylesheet" href="multiplication-app.css">
  </head>
  <body ng-init="data='x'">
<div multiplication-table x="5" y="5">
  {{ multiplication.value }}
</div>
<script type="text/javascript" src="//code.angularjs.org/1.3.6/angular.js"></script>
<script src="multiplication-app.js"></script>
  </body>
</html>

乘法应用程序.js

var ngModule = angular.module('MultiplicationApp', [])
ngModule.directive('multiplicationTable', [function() {
  return {
    templateUrl : 'multiplication-table-tpl.html',
    controllerAs : 'ctrl',
    transclude: true,
    bindToController: true,
    scope: {
      x : '=',
      y : '='
    },
    controller : function() {
      var x = this.x || 0;
      var y = this.y || 0;
      var table = this.rows = [];
      for(var i=0;i<y;i++) {
        var array = table[i] = [];
        for(var j=0;j<x;j++) {
          array.push(1); 
        }
      }
    }
  }
}]);
ngModule.directive('multiplicationCell', [function() {
  return {
    controllerAs : 'multiplication',
    bindToController: true,
    scope: {
      x : '=',
      y : '='
    },
    controller : function() {
      var x = this.x || 0; //why does this does not resolve the x="$index+1" attribute in the directive.
      var y = this.y || 0; //why does this does not resolve the y="$parent.$index+1" attribute in the directive.
      this.value = x * y;
      // console.log(this);
    }
  };
}]);

乘法表.tpl.html

<div ng-repeat="row in ctrl.rows track by $index">
  <div ng-repeat="cell in row track by $index">
    <div multiplication-cell
         x="$index+1"
         y="$parent.$index+1"
         ng-transclude>
    </div>
  </div>
</div>

我不明白为什么我无法从内部嵌套标签内的multiplication控制器访问multiplication.value

我创建了这个 plunk 来演示这一点。

普伦克演示 2

我正在寻找以下问题的答案:

  1. 为什么第二个 Plunk 没有按预期工作?
  2. 如何使用最小的更改使第二个 plunk 工作。而且这个解决方案不应该与第一个 Plunker 相同。

注意:multiplicationCell实现与multiplicationTable类似,但仍然不起作用。

基本上,为multiplication创建一个模板,其中包含我们正在包含的值。

controllerAs : 'multiplication',
templateUrl: 'multiplication.tpl.html',
bindToController: true,
scope: {
  x : '=',
  y : '='
},
controller : function() {
  var x = this.x || 0;
  var y = this.y || 0;
  this.value = x * y;
  // console.log(this);
}
}]);

为了访问乘法值,您需要将值传递给它自己的模板,所以我为子"multiplication.tpl.html"创建了模板,您需要的是实现。

乘法.tpl.html

{{ multiplication.value }}

找到您的答案:http://plnkr.co/edit/glssXrvbVpP2UjDgu3Ed?p=preview

我希望这个解释可以消除你的疑虑。

谢谢和干杯!

最新更新