2014-10-19 138 views
0

有没有任何方法将带模板url的字符串对象传递给指令? 我的解决方案无法正常工作。将模板url传递给angularjs指令

的Javascript:

function moduleView() { 
    return{ 
     restrict: 'A', 
      templateUrl: function (elem, attr) { 
       return attr.url; 
       } 
      }; 
     }; 
function ModulesCtrl($scope, ModulesService) { 
    $scope.modules = []; 

    $scope.run = function() { 
     ModulesService.loadModules(function (items) { 
      $scope.modules = items; 
     }); 
    }; 

    $scope.run(); 
}; 

HTML(玉):

ul(ng-repeat="item in modules") 
    div(module-view url="item.path") 

item.path与URLØ模板的字符串。

但是这段代码不起作用。我有这个错误:

Error: [$compile:tpload] Failed to load template: item.path 
+0

'return attr.url;'将返回实际的字符串'item.path',而不是存储在'path'属性中的url。你需要在返回之前插入字符串。问题在于'templateUrl'函数在内插发生之前运行。也没有可用的'$ scope',只有'$ rootScope'。从'$ rootScope'引用项目吗? – tasseKATT 2014-10-19 07:16:26

+0

控制器'函数ModulesCtrl($ scope,ModulesService)中$ scope引用的项{ $ scope.modules = []; $ scope.run = function(){ ModulesService.loadModules(function(items){ $ scope.modules = items; }); }; $ scope.run(); };'item是数组模块'ul的元素(ng-repeat =“模块中的项目)” – Egor 2014-10-19 07:28:52

+1

模板:“

” – harishr 2014-10-19 07:33:19

回答

0

有多种方法可以做到这一点 - 最简单的方法是使用ng-include来包含模块的模板。

查看此plunker为例。

当然,还可以将一个scope变量添加到指令中,并让它通过该变量执行ng-include

相关问题