2016-01-19 116 views
0

有沒有辦法動態更改指令的templateUrl並編譯它?如何在angularJS中動態更改指令的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> 

這是從角文件的代碼,說如果我想點擊按鈕來改變myCustomer模板,我該怎麼辦呢?

+0

當然可以,並說明這樣做的開發者指南,指令(https://docs.angularjs.org/guide/directive)英寸如果你想要一個更具體的答案,你應該提供一些代碼來顯示你所嘗試過的。 – Claies

+0

@Claies謝謝,能否指出該頁面上的哪一部分與更改templateUrl相關? – Kuan

+0

你的意思是說「templateUrl也可以是一個函數,它返回一個HTML模板的URL加載並用於指令」? – Claies

回答

0

看看下面的代碼。 templateUrl是HTML網址。

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

謝謝,你能告訴我如何使用這個$ templateCache來改變特定的指令模板 – Kuan

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