使用指令时,我有时发现需要通过嵌套指令传递数据,即使中间指令不使用数据,它们也需要将其传递给子指令。这很烦人,因为它耦合了指令并使接线变得非常困难。
考虑这个例子:MainCtrl 在数组中保存一些数据并使用“first-directive”。然后该指令使用“第二指令”,它需要从 MainCtrl 访问数据。因此,“first-directive”需要从 MainCtrl 获取数据并将其传递给它 - 而它本身对数据不执行任何操作:
<body ng-controller="MainCtrl as mainCtrl">
<first-directive data="mainCtrl.items"></first-directive>
</body>
和 JavaScript:
app.controller('MainCtrl', function($scope) {
var self = this;
self.items = ["first", "second"];
});
app.directive('firstDirective', function() {
return {
scope: {
data: '='
},
template: '<second-directive data="data"></second-directive>'
};
});
app.directive('secondDirective', function() {
return {
scope: {
data: '='
},
template: 'second directive data: {{data}}'
};
});
如何更改上述代码以使“first-directive”不需要了解数据?这是 Angular 中的常见问题吗?这通常是如何解决的?当涉及更多指令嵌套时,问题会变得更糟。
骗子:https://plnkr.co/edit/aKWBq5DLOLFvamk6gx4e?p=preview
编辑:我找到了一篇讨论此问题的博客文章。它建议在嵌套指令上使用“require”。你怎么认为? http://www.codelord.net/2014/03/30/writing-more-maintainable-angular-dot-js-directives/
最佳答案
您可以通过存储需要在可注入(inject)两个指令的服务中传递的内容来实现此目的。这是其他人这样做的一个很好的例子:
关于javascript - Angular - 将数据传递给嵌套指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39039653/