Angular.js 指令动态加载模板

Angular.js 指令动态加载模板

ZKEASOFT February 24, 2017


Angular.js 指令的 templateURL 是不能动态指定的,只会被加载一次,那么该如何动态加载呢?

.directive('dynamicTemplate', function() {
   return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           scope.getContentUrl = function() {
                return 'content/excerpts/template-' + attrs.ver + '.html';
           }
       },
       template: '<div ng-include="getContentUrl()"></div>'
   }
});

或者使用:$observe

.directive('dynamicTemplate', function() {
   return {
       restrict: 'E',
       link: function(scope, element, attrs) {
           scope.contentUrl = 'content/excerpts/template-' + attrs.ver + '.html';
           attrs.$observe("ver",function(v){
               scope.contentUrl = 'content/excerpts/template-' + v + '.html';
           });
       },
       template: '<div ng-include="contentUrl"></div>'
   }
});

微信公众号