Может ли директива angular требовать собственный контроллер?
Это простой вопрос, но я не могу найти соответствующую документацию...
Я пытаюсь выяснить, может ли директива angular наследовать родительский контроллер, а также его собственный. Рассмотрим следующие примеры:
Простой наследование от себя
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
}
}
});
Является ли эта возможная/правильная форма (или это какой-то анти-шаблон, о котором я не знаю)?
Ответы
Ответ 1
Хорошо, что оказалось намного более очевидным, чем я думал... небольшая пробная версия и ошибка показали, что директива также может потребовать самого себя.
Правильный способ наследования родительских + локальных контроллеров выглядит следующим образом:
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
}
}
});