如何在angularJS中动态更改指令的templateUrl

时间:2016-01-19 23:50:12

标签: angularjs angularjs-directive

有没有办法动态更改指令的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的代码,如果我想点击该按钮来更改myCustomer模板,我该怎么做?

2 个答案:

答案 0 :(得分:0)

请看下面的代码。 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);
    }

答案 1 :(得分:0)

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);
        });
    }
  }
});