gpt4 book ai didi

javascript - Angular Directive(指令)可以需要自己的 Controller 吗?

转载 作者:行者123 更新时间:2023-12-03 02:04:58 25 4
gpt4 key购买 nike

这是一个简单的问题,但我似乎找不到任何相关文档......

我试图找出 Angular Directive(指令)是否可以继承父 Controller 以及它自己的。考虑以下示例:

简单的 self 继承

app.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomething = function() {

};
},
link: function($scope, el, attrs, ctrl) {
// ctrl now contains `doSomething`
}
}
});

从父级继承

app.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomething = function() {

};
}
}
});
app.directive('widget', function() {
return {
scope: true,
require: '^screen',
link: function($scope, el, attrs, ctrl) {
// ctrl now contains `doSomething` -- inherited from the `screen` directive
}
}
});

甚至还有多重继承...

app.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomething = function() {

};
}
}
});
app.directive('widget', function() {
return {
scope: true,
require: ['^screen','^anotherParent'],
link: function($scope, el, attrs, ctrl) {
// ctrl[0] now contains `doSomething` -- inherited from the `screen` directive
// ctrl[1] now contains the controller inherited from `anotherParent`
}
}
});

我不知道如何使指令继承父 Controller 及其自身的 Controller 。就像这样:

app.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomething = function() {

};
}
}
});
app.directive('widget', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
// isolated widget controller
},
link: function($scope, el, attrs, ctrl) {
// I need the `screen` controller in ADDITION to the isolated widget controller accessible in the link
}
}
});

这是可能/正确的形式(还是我不知道的某种反模式)?

最佳答案

事实证明,这比我想象的要明显得多...一点试验和错误表明指令实际上也可以要求自身。

继承父级+本地 Controller 的正确方法似乎是:

app.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomething = function() {

};
}
}
});
app.directive('widget', function() {
return {
scope: true,
require: ['^screen','widget'],
controller: function($scope) {
this.widgetDoSomething = function() {
};
},
link: function($scope, el, attrs, ctrl) {
// ctrl[0] contains the `screen` controller
// ctrl[1] contains the local `widget` controller
}
}
});

关于javascript - Angular Directive(指令)可以需要自己的 Controller 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24925502/

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