Javascript 角度指令是否需要自己的控制器?
这是一个简单的问题,但我似乎找不到任何相关的文档 我试图找出angular指令是否既可以继承父控制器,也可以继承自己的控制器。考虑下面的例子: 简单的自我继承Javascript 角度指令是否需要自己的控制器?,javascript,angularjs,Javascript,Angularjs,这是一个简单的问题,但我似乎找不到任何相关的文档 我试图找出angular指令是否既可以继承父控制器,也可以继承自己的控制器。考虑下面的例子: 简单的自我继承 app.directive('screen', function() { return { scope: true, controller: function() { this.doSomething = function() { }; }, link: functio
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`
}
}
});
我不明白的是如何使指令同时继承父控制器和它自己的控制器。像这样:
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
}
}
});
这是可能的/正确的形式吗(或者是某种我不知道的反模式)?事实证明,这比我想象的要明显得多。。。一点尝试和错误表明,指令实际上也可以要求自己 继承父级+本地控制器的正确方法似乎是:
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
}
}
});
我现在就是这么做的。。。我的搜索是希望发现一种更“优雅”的方法。我猜就是这样做的=/我很高兴你问了这个问题,我花了很长时间才弄明白。为什么你需要^screen指令?