steve
steve

Reputation: 3465

AngularJS Template Replace directive not working

I have a templating directive that is almost working the way I want, simple version works :-

<div bw-template-replace>
  <template>This is template text, replace [[#this]] please</template>
  <this>text replaced</this>
</div>

expands to

<div bw-template-replace><span>This is template text, replace text replaced please</span></div>

However, if I embed other directives they dont fully work as expected.

See my plunk http://plnkr.co/edit/dLUU2CMtuN5WMZlEScQi?p=preview

At the end of the directive's link function I $compile the resulting text/node which works for {{scope interpolated text}} but does not work for embedded directives using the same scope.

The reason I need this is because I am using ng-translate for an existing ng-app and I want to use the existing English text as keys for translation lookups. An uncommon translation case is where we have HTML like the following (extract from the app), the [[#ageInput]] and [[#agePeriod]] 'arguments' may appear at different places in other languages, as I understand it ng-translate has no real support for this scenario currently.

<div class="row-fluid">
    <div class="span12" translate bw-template-replace>
        <template>
            If current version of media has not been read for [[#ageInput]] [[#agePeriod]]
        </template>
        <ageInput><input type=number ng-model="policy.age" style="width:50px"/></ageInput>
        <agePeriod><select style="width:100px" ng-model="policy.period" ng-options="p for p in periods" /></agePeriod>
    </div>
</div>

Any help much appreciated.

I love having to work through these scenarios when you are a newbie at something as it really forces you to understand what is happening. I now have it working, basically my previous directive I found several ways of just replacing the html in the hope Angular would magically sort everything out. Now I have a better understanding of transclusion and in particular the transclusion function I made it work as desired. The cloned element passed into $transcludeFn already has scope attached and has been $compiled, so my function now parses the template text and generates individual textElement's and moves the argument elements around to suit the template.

My Current Solution

.directive('TemplateReplace', ['$compile', '$document', '$timeout',
  function ($compile, $document, $timeout) {
      return {
          restrict: 'AC',
          transclude: true,
          link: function (scope, iElement, iAttrs, controller, transclude) {
              transclude(scope, function (clone, $scope) {
                  $timeout(function () {
                      // Our template is the first real child element (nodeType 1)
                      var template = null;
                      for (var i = 0, ii = clone.length; i < ii; i++) {
                          if (clone[i].nodeType == 1) {
                              template = angular.element(clone[i]);
                              break;
                          }
                      }

                      // Remember the template's text, then transclude it and empty its contents
                      var html = angular.copy(template.text());
                      iElement.append(template);        // Transcluding keeps external directives intact
                      template.empty();                 // We can populate its inards from scratch

                      // Split the html into pieces seperated by [[#tagname]] parts
                      if (html) {
                          var htmlLen = html.length;

                          var textStart = 0;
                          while (textStart < htmlLen) {
                              var tagName = null,
                                tagEnd = htmlLen,
                                textEnd = htmlLen;

                              var tagStart = html.indexOf("[[#", textStart);
                              if (tagStart >= 0) {
                                  tagEnd = html.indexOf("]]", tagStart);
                                  if (tagEnd >= 0) {
                                      tagName = html.substr(tagStart + 3, tagEnd - tagStart - 3);
                                      tagEnd += 2;
                                      textEnd = tagStart;
                                  }
                              }

                              // Text parts have to be created, $compiled and appended
                              var text = html.substr(textStart, textEnd - textStart);
                              if (text.length) {
                                  var textNode = $document[0].createTextNode(text);
                                  template.append($compile(textNode)($scope));
                              }

                              // Tag parts are located in the clone then transclude appended to keep external directives intact (note each tagNode can only be referenced once)
                              if (tagName && tagName.length) {
                                  var tagNode = clone.filter(tagName);
                                  if (tagNode.length) {
                                      template.append(tagNode);
                                  }
                              }
                              textStart = tagEnd;
                          }
                      }
                  }, 0);
              });
          }
      };
  }
]);

Upvotes: 0

Views: 1468

Answers (1)

Shripal Soni
Shripal Soni

Reputation: 2448

If I have understood your question properly, I guess the issue is your directive is getting executed before ng-repeat prepares dom.So you need to do DOM manipulation in $timeout.

Check this plunker for working example.

Here is a nice explanation of similar problem: https://stackoverflow.com/a/24638881/3292746

Upvotes: 1

Related Questions