Reputation: 1349
I've made a very simple paragraph directive based on HTML <p>
tag.
angular.module('myApp').directive('paragraph', function() {
return {
restrict: 'E',
transclude: true,
controller: function() {
var vm = this;
vm.text = "Paragraph text from controller"
},
controllerAs: 'ParagraphViewModel',
template: '<p ng-transclude>{{ParagraphViewModel.text}}</p>'
}
});
I am using that directive in my html as follow:
<paragraph>This is a very simple paragraph</paragraph>
<paragraph></paragraph>
And I have an input which I've bound it to ParagraphViewModel.text
.
<input type="text" ng-model="ParagraphViewModel.text">
The problem is, when I change the input, the second <paragraph>
changes as expected, But first ones value does not.
Please check this JSBin to see it in action.
Upvotes: 1
Views: 500
Reputation: 4059
I guess what you're trying to achieve here is to pass your directive a default text and then change it with bound input.
You can achieve that by using Isolated Scopes. Here's how you should do it:
In your View :
<div ng-app="myApp">
<paragraph pgtext="Foo" pgmodel="bar"></paragraph>
<paragraph>{{bar}}</paragraph>
<input type="text" ng-model="bar">
</div>
In your App:
angular.module('myApp',[]);
angular.module('myApp').directive('paragraph', function() {
return {
restrict: 'E',
transclude: true,
scope: {
pgmodel: '=',
pgtext: '@'
},
template: '<p ng-transclude>{{pgmodel || pgtext}}</p>'
}
});
DEMO: JSBin
Upvotes: 1
Reputation: 1420
Take another look at the docs, especially at this particular example.
You see, when Angular transcludes your content in
<paragraph>This is a very simple paragraph</paragraph>
it completely forgets about {{ParagraphViewModel.text}}
binding in the directive's template because all the content of <p ng-transclude>
will be replaced by the content from <paragraph>
tag.
The second case is working as you expect it to simply because content replacement does not happen and Angular defaults to the content from your template.
Upvotes: 2