I'm sure this question has been asked before but I'm having a hard time figuring out the right thing to search for.
I have an app with a lot of boilerplate code, such as paginators, toggles, filters, etc. I don't want to turn these things into directives as that seems like overkill. Currently I'm using ng-include to dry up my HTML, but in my directives I still have a lot of boilerplate scoped functions.
What I want to know is if/how I can load these functions from a module and have them bound to the scope automatically.
Right now I have this:
.directive('somethingAwesome', ['$http', '$timeout', function($http, $timeout) {
return {
replace: true,
templateUrl: '/assets/awesome_sauce.html',
transclude: false,
scope: true,
controller: ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
// Public Functions List
$scope.next = next;
$scope.prev = prev;
$scope.filter = filter;
// ...
// Public Functions Definitions
function next() {
// Do something
}
function prev() {
// Do something
}
function filter() {
// Do something
}
// ...
}]
}
}])
I want to do something more like this:
.directive('somethingAwesome', ['$http', '$timeout', function($http, $timeout) {
return {
replace: true,
templateUrl: '/assets/awesome_sauce.html',
transclude: false,
scope: true,
controller: ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {
include boilerplate;
}]
}
}])
(function boilerplate() {
// Public Functions List
$scope.next = next;
$scope.prev = prev;
$scope.filter = filter;
// ...
// Public Functions Definitions
function next() {
// Do something
}
function prev() {
// Do something
}
function filter() {
// Do something
}
// ...
return something;
})()
The key here is that simply including boilerplate
binds all the functions to the scope of whatever directive or controller included it. Even if I still have to manually bind each function from boilerplate
to the scope, something like this is still useful as it drys up a lot of code.
Is this possible, and if so, how?