Reputation: 9002
Using transclude on directives is very useful if you want the scope of your controller to be bound to the HTML that you are passing in.
How would you accomplish the reverse? (have access to the directive's scope from within the controller)
This is an example of what I want to achieve:
<my-directive model='controllerModel'>
{{directiveModel}}
</my-directive>
.directive(function () {
return {
transclude: true,
template: '<div ng-transclude></div>'
scope: {
directiveModel: '=model'
}
}
})
In this example, the scope property 'directiveModel' is accessible from within the HTML that is "transcluded".
This will not work of course, because the scope of the controller is bound to the HTML that is passed in.
I am not sure how to achieve this (having access to the scope of the directive from within the controller) in the best way.
The best method I can think of is to not use transclude, and to instead use .html() to inject the HTML into a template, and then using the $interpolate service to bind the directives scope to the HTML.
The problem is that if you define a template for the directive, angular will replace the HTML you are "passing in" with the directives HTML before you have access to it.
Upvotes: 1
Views: 754
Reputation: 2506
If you want to make directiveModel accessible inside the transcluded content you can use the transclude function to perform the transclusion process manually and not use ng-transclude. When you use the transclude function you can change the scope to be used.
app.directive('myDirective', function(){
return {
restrict: 'E',
transclude: true,
template: '<div></div>',
scope: {
directiveModel: '=model'
},
link: function(scope, element, attrs, ctrl, transcludeFn){
transcludeFn(scope, function(clonedTranscludedContent ) {
element.append(clonedTranscludedContent);
});
}
}
});
Upvotes: 3