Here is the issue that needs to be addressed. I am working with a third party directive named main-directive.
app.directive('mainDirective', function() {
return {
scope: {
foo: '&'
// attrs
},
controller: function($scope) {
$scope.click = function() {
window.alert($scope.foo());
}
},
template: '<button ng-click="click()">Click me</button>'
}
});
My goal is to create a custom directive called parent-directive which will set default values for the attributes of the third party directive.
app.directive('parentDirective', function() {
return {
scope: {
foo: '&?',
attr2: '='
// lots of attrs
},
controller: function($scope) {
$scope.attr1 = "some default value"
$scope.foo = function() {
return "not overrided"
}
if (this.foo) {
$scope.foo = this.foo
}
},
template: '<div class="some-styling"><main-directive foo="foo()" attr1="attr1" attr2="attr2"></main-directive></div>'
}
});
If I need to create another directive, let's say child-directive, which should inherit the logic from parent-directive. Overloading attributes can be easily achieved using the "compile" function. But how can functions be overridden?
app.directive('childDirective', function() {
return {
scope: false,
require: 'parentDirective',
link: function(scope, element, attr, controller) {
controller.foo = function() {
return "overrided";
}
},
compile: function(element, attr) {
attr.attr2 = "attr2";
}
}
});
The entire process could be simplified by utilizing a child scope instead of an isolated one. Alternatively, extending through a template could also work. However, copying the parent's "scope" and "template" definition to the child-directive and forwarding all non-default attributes might not be the most elegant solution.
Hence, the crucial question remains, is there a way to override a function from the parent-directive using an isolated scope without having to forward attributes.
Take a look at the DEMO for reference.