我用这个解决方案用模板替换根节点,这是可以的。但后来有必要动态更改模板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>
尝试.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>