正如标题所示,我在使用嵌套自定义指令的 Angular 项目上遇到了一些问题。我正在创建一个界面,允许用户通过单击复选框来过滤搜索结果的 JSON 提要。 指令模板层次结构如下:
<filtergroup>
<filter></filter>
</filtergroup>
我似乎能够访问过滤器组模板中过滤器组指令的 Controller 中定义的变量。但是,尽管使用了
,但我无法从子指令中访问相同的变量require: '^filtergroup'
以下是我的指令:
.directive('filtergroup', [function(){
return{
restrict: 'E',
transclude: true,
scope: { },
template: '<div><ng-transclude></ng-transclude>{{filtergroup.variable}}</div>',
bindToController: true,
controllerAs: 'filtergroup',
replace: true,
controller: function() {
var self = this;
self.variable = "blah";
}
};}])
.directive('filter', [function(){
return {
restrict: 'E',
template: '<div>{{filtergroup.variable}}</div>',
require: '^filtergroup',
scope: {},
link: function(scope, elem, attr, filtergroupCtrl){
scope.active = false;
}
};}]);
我还在以下位置创建了该问题的简化 Codepen:
http://codepen.io/decodedcreative/pen/NrNqXm
任何帮助都会很棒,因为这让我发疯!谢谢
最佳答案
通过说 require: '^filtergroup'
您只是要求将 filtergroup
的 Controller 注入(inject)链接函数。然后就看你如何使用它了。
就您而言,您可以添加对 filter
范围的 filtergroupCtrl
引用:
.directive('filter', [function(){
return {
// ...
template: '<div>{{filtergroup.variable}}</div>',
link: function(scope, elem, attr, filtergroupCtrl){
scope.filtergroup = filtergroupCtrl;
// ...
}
};
}]);
这样您就可以按照您尝试的方式在子模板中访问它:
<div>{{filtergroup.variable}}</div>
关于javascript - Angular JS - 使用带有嵌套自定义指令的 ControllerAs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37773345/