When defining a directive controller, there are two main approaches outlined below for consideration:
Option 1:
angular.module('app')directive('AppHeader', AppHeader);
function AppHeader() {
var headerDirective = {
restrict: 'E',
templateUrl: 'header.html',
link: linkFunc,
controllerAs: 'vm',
controller: NavCtrl
};
return headerDirective;
function linkFunc(scope, element, attrs) {
/* */
}
}
NavCtrl.$inject = ['$scope', 'Service'];
function NavCtrl($scope, Service) {
var vm = this;
/* Controller actions */
}
In the above code snippet, the controller is separated from the directive function block.
Option 2:
angular.module('app').directive('AppHeader', AppHeader);
function AppHeader()
{
var headerDirective = {
restrict: 'E',
templateUrl: 'header.html',
link: linkFunc,
controllerAs: 'vm',
controller: NavCtrl
};
return headerDirective;
function linkFunc(scope, element, attrs) {
/* */
}
NavCtrl.$inject = ['$scope', 'Service'];
function NavCtrl($scope, Service) {
var vm = this;
/* Controller actions */
}
}
In Option 2, the controller is added within the directive function block.
Which of these methods do you believe to be the best practice when creating and defining Directive controllers, and why? Your input is much appreciated!