1

I used this solution to replace root node with template and it was ok. But then it was necessary to change template url dynamically. In this case previous template remains on page and new template adds after it on template url changing. Is it possible to avoid this behavior somehow? I still need to replace root element because of makeup troubles.

angular.module("app", [])
  .directive('includeReplace', function() {
    return {
      require: 'ngInclude',
      restrict: 'A',
      link: function(scope, el, attrs) {
        el.replaceWith(el.children());
      }
    };
  })
  .controller("MainController", function() {
    this.tpl = "tpl1.html";
    this.toggle_tpl = function() {
      this.tpl = (this.tpl == 'tpl1.html') ? 'tpl2.html' : 'tpl1.html';
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MainController as mCtrl">
    <script type="text/ng-template" id="tpl1.html">
      <div>First template</div>
    </script>
    <script type="text/ng-template" id="tpl2.html">
      <div>Second template</div>
    </script>

    <button ng-click="mCtrl.toggle_tpl()">toggle</button>

    <div ng-include="mCtrl.tpl" include-replace>
    </div>
  </div>
</div>
Community
  • 1
  • 1
Anton
  • 2,217
  • 3
  • 21
  • 34

1 Answers1

1

Try .html() instead of .replaceWith()

angular.module("app", [])
  .directive('includeReplace', function() {
    return {
      require: 'ngInclude',
      restrict: 'A',
      link: function(scope, el, attrs) {
        el.html(el.children().html()); // My changes in the line
      }
    };
  })
  .controller("MainController", function() {
    this.tpl = "tpl1.html";
    this.toggle_tpl = function() {
      this.tpl = (this.tpl == 'tpl1.html') ? 'tpl2.html' : 'tpl1.html';
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MainController as mCtrl">
    <script type="text/ng-template" id="tpl1.html">
      <div>First template</div>
    </script>
    <script type="text/ng-template" id="tpl2.html">
      <div>Second template</div>
    </script>

    <button ng-click="mCtrl.toggle_tpl()">toggle</button>

    <div ng-include="mCtrl.tpl" include-replace>
    </div>
  </div>
</div>
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
  • In this case the outer `
    ` remains in markup. I need to replace it with template's content. For example if original markup is `
    `, the result should be `
    First template
    ` in initial state and `
    First template
    ` if `this.tpl` is toggled. May be it is not possible. In this case I'll try to fix elements' positions in css.
    – Anton Nov 02 '15 at 14:32