Search code examples
javascriptangularjsangularjs-ng-transclude

angular directive with ng-transclude


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.


Solution

  • 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