【问题标题】:Dynamic src with include-replace包含替换的动态 src
【发布时间】:2015-11-02 14:14:21
【问题描述】:

我使用this 解决方案将根节点替换为模板,没问题。但随后有必要动态更改模板 url。在这种情况下,以前的模板保留在页面上,新模板在模板 url 更改后添加。是否有可能以某种方式避免这种行为?由于化妆问题,我仍然需要更换根元素。

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>

【问题讨论】:

    标签: angularjs angularjs-ng-include


    【解决方案1】:

    尝试.html() 而不是.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>

    【讨论】:

    • 在这种情况下,外部&lt;div ng-include="mCtrl.tpl" include-replace&gt; 保留在标记中。我需要用模板的内容替换它。例如,如果原始标记为&lt;div ng-include="mCtrl.tpl" include-replace&gt;&lt;/div&gt;,则初始状态下的结果应为&lt;div&gt;First template&lt;/div&gt;,如果切换this.tpl,则结果应为&lt;div&gt;First template&lt;/div&gt;。可能是不可能的。在这种情况下,我将尝试修复元素在 css 中的位置。
    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 2011-05-13
    相关资源
    最近更新 更多