如何动态更改指令';angularJS中的s模板URL

如何动态更改指令';angularJS中的s模板URL,angularjs,angularjs-directive,Angularjs,Angularjs Directive,有没有办法动态更改指令的templateUrl并编译它 angular.module('docsTemplateUrlDirective', []) .controller('Controller', ['$scope', function($scope) { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) .directive('myCustomer', function()

有没有办法动态更改指令的templateUrl并编译它

angular.module('docsTemplateUrlDirective', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.customer = {
    name: 'Naomi',
    address: '1600 Amphitheatre'
  };
}])
.directive('myCustomer', function() {
  return {
    templateUrl: function(elem, attr){
      return 'customer-'+attr.type+'.html';
    }
  };
});
html是这样的:

<div ng-controller="Controller">
    <button> Change my customer template</button>
    <my-customer></my-customer>
</div>

更改我的客户模板

这是Angular Doc中的代码,比如说,如果我想单击该按钮更改我的客户模板,我该怎么做?

查看下面的代码。templateUrl是HTML Url

 template = $templateCache.get(templateUrl);
    if (typeof template === "undefined") {
        $http.get(templateUrl)
          .success(function (data) {
              $templateCache.put(templateUrl, data);
              def.resolve(data);
          }).error(function (error) {
              console.log(error);
          });
    } else {
        def.resolve(template);
    }

是的,您可以这样做,相关说明在《开发人员指令指南》中()。如果您想得到更具体的答案,您应该提供一些代码来显示您的尝试。@Claies谢谢,您能指出该页面上与更改templateUrl相关的部分吗?您的意思是说“templateUrl也可以是一个函数,返回要加载并用于指令的HTML模板的URL”?@Claies是的,您能告诉我如何动态调用它,而不是初始阶段吗?方法是将参数传递给由生成templateUrl的函数计算的指令。如果您想要更具体的,您必须提供一些代码。谢谢,您能告诉我如何使用$templateCache来更改特定的指令模板吗
app.directive('panelDir', ['$templateCache', '$http', '$q', '$compile', function ($templateCache, $http, $q, $compile) {

var getTemplate = function (contentType) {
    var def = $q.defer();
    var template = '';
    var templateUrl = "";

    switch (contentType) {
        case 'setting':
            templateUrl = "Panel.html";
            break;
    }        
    template = $templateCache.get(templateUrl);
    if (typeof template === "undefined") {
        $http.get(templateUrl)
          .success(function (data) {
              $templateCache.put(templateUrl, data);
              def.resolve(data);
          }).error(function (error) {
              console.log(error);
          });
    } else {
        def.resolve(template);
    }

    return def.promise;
}

return {
    restrict: 'A',
    link: function (scope, element, attrs) {           
        getTemplate(attrs['paneltype']).then(function (data) {
            data = $compile(data)(scope);
        });
    }
  }
});