Is possible to do the following in Angular?
<div ng-controller="MainCtrl" ng-init="name='World'">
<test name="Matei">Hello {{name}}!</test> // I expect "Hello Matei"
<test name="David">Hello {{name}}!</test> // I expect "Hello David"
</div>
My directive is simple but it's not working:
app.directive('test', function() {
return {
restrict: 'E',
scope: {
name: '@'
},
replace: true,
transclude: true,
template: '<div class="test" ng-transclude></div>'
};
});
I also tried to use the transclude function to change the scope and it works. The only problem is that I loose the template.
app.directive('test', function() {
return {
restrict: 'E',
scope: {
name: '@'
},
transclude: true,
template: '<div class="test" ng-transclude></div>',
link: function(scope, element, attrs, ctrl, transclude) {
transclude(scope, function(clone) {
element.replaceWith(clone);
});
}
};
});
Is it possible to do this while keeping the template in place and clone to be appended into the element with ng-transclude
attribute?
Here is a Plnkr link you could use to test your solution: http://plnkr.co/edit/IWd7bnhzpLmlBpoaoJct?p=preview
That happened to you because you were too aggressive with the element.
You can do different things instead of
replaceWith
that will... replace the current element.You can append it to the end, prepend it... pick one template element and insert it inside... Any DOM manipulation. For example:
Here I decided to put it after the element, so you could expect:
Notice I did not included
ng-transclude
on the template. It is not needed because you're doing that by hand.So TL;DR;: Play with the element, don't just replace it, you can insert the transcluded html where you want it, just pick the right element, and call the right method on it.
For the sake of completeness here is another example: http://plnkr.co/edit/o2gkfxEUbxyD7QAOELT8?p=preview