sadrzadehsina sadrzadehsina - 1 month ago 18
AngularJS Question

angular directive with ng-transclude

I have 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 bind it to
ParagraphViewModel.text
.

<input type="text" ng-model="ParagraphViewModel.text">


The problem is when I change the input, the second
<paragraph>
works as expected. But the text of first one does not.

please check this jsbin to view it in action.

Answer

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