gpt4 book ai didi

javascript - 在嵌套指令场景中从内部指令(模板内部)传递属性

转载 作者:行者123 更新时间:2023-11-27 22:48:43 24 4
gpt4 key购买 nike

引用以下代码片段:

Plunker Demo 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>

乘法-app.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 Controller 访问 multiplication.value

我创建了这个小东西来演示这一点。

Plunker Demo 2

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

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

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

最佳答案

基本上,为乘法创建一个模板,其中包含我们要嵌入的值。

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 }}

找到 Plunker 来获取答案:http://plnkr.co/edit/glssXrvbVpP2UjDgu3Ed?p=preview

我希望这个解释能消除您的疑虑。

谢谢并欢呼!

关于javascript - 在嵌套指令场景中从内部指令(模板内部)传递属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38233849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com