Javascript 如何在Angularjs中使用新模板重新呈现指令?

Javascript 如何在Angularjs中使用新模板重新呈现指令?,javascript,angularjs,Javascript,Angularjs,我正在做一个简单的web项目,但我对Angular指令有一个问题。它不能重新呈现html,只能在第一次呈现。这是我的代码: app.directive('dyTemplate',['$compile',function($compile){ var getTemplate=函数(contentType){ 模板映射={ 1: '', 2: '', 3: '' }; 返回templateMap[contentType]; } 返回{ 限制:“EA”, 链接:函数(范围、元素、属性){ //默认加

我正在做一个简单的web项目,但我对Angular指令有一个问题。它不能重新呈现html,只能在第一次呈现。这是我的代码:

app.directive('dyTemplate',['$compile',function($compile){
var getTemplate=函数(contentType){
模板映射={
1: '',
2: '',
3: ''
};
返回templateMap[contentType];
}
返回{
限制:“EA”,
链接:函数(范围、元素、属性){
//默认加载模板
html(getTemplate(1));
replaceWith($compile(element.html())(scope));
scope.changemplate=函数(templateId){
html(getTemplate(templateId));
replaceWith($compile(element.html())(scope));
}
}
}
}
]);

您使用的是
元素.replaceWith()
,它第一次从DOM中删除元素,但随后的调用不会更改DOM,因为
元素
不再在DOM中

我还怀疑您使用
$compile
会使事情过于复杂。在大多数情况下,只在指令中使用
template
选项更好(因为更简单)。Angular然后为您处理编译。在模板中,您可以使用
{{}
插值、调用函数,并在需要时使用
ngIf
更改显示内容,就像任何已编译的模板一样,并且通常不需要手动编译或修补DOM

这方面的一个例子见

var-app=angular.module('myapp',[]);
应用程序指令('dyTemplate',函数(){
返回{
限制:“EA”,
作用域:{},
模板:“”,
链接:函数(范围、元素、属性){
scope.templateId=1;
scope.nextTemplateId=函数(){
var templateMap={
1: 2,
2: 3,
3: 1
};
返回templateMap[scope.templateId];
};
scope.shownettemplate=函数(){
scope.templateId=scope.nextTemplateId();
};
}
};
});

你能设置一个PlunkYep,我是Plunk:谢谢你的回答,Michal。这只是简单的测试代码。在我的项目中,模板比这更复杂。如果元素不再存在,我想我需要找到新的方法来更改模板。
app.directive('dyTemplate', ['$compile',function($compile) {
    var getTemplate = function(contentType) {
      templateMap = {
        1: '<div><a href="" ng-click="changeTemplate(2)"> Change to Template 2</a></div>',
        2: '<div><a href="" ng-click="changeTemplate(3)"> Change to Template 3</a></div>',
        3: '<div><a href="" ng-click="changeTemplate(1)"> Change to Template 1</a></div>'
      };
      return templateMap[contentType];
    }
    return {
      restrict: 'EA',
      link: function(scope, element, attrs) {
        // default load template
        element.html(getTemplate(1));
        element.replaceWith($compile(element.html())(scope));
        scope.changeTemplate = function(templateId) {
          element.html(getTemplate(templateId));
          element.replaceWith($compile(element.html())(scope));
        }
      }
    }
  }
]);
var app = angular.module('myapp',[]); 
app.directive('dyTemplate', function() {
  return {
    restrict: 'EA',
    scope:{},
    template: '<div><a href="" ng-click="showNextTemplate()"> Change to Template {{nextTemplateId()}}</a></div>',
    link: function(scope, element, attrs) {
      scope.templateId = 1;

      scope.nextTemplateId = function() {
        var templateMap = {
          1: 2,
          2: 3,
          3: 1
        };
        return templateMap[scope.templateId];
      };

      scope.showNextTemplate = function() {
        scope.templateId = scope.nextTemplateId();
      };
    }
  };
});