【问题标题】:AngularJS Dynamic TemplateUrl ValueAngularJS 动态 TemplateUrl 值
【发布时间】:2014-05-13 21:07:07
【问题描述】:

我正在尝试将一个已经动态的值传递给我的指令,以获取该值的 templateUrl。让我用一些源代码解释一下:

<p ng:repeat="cell in field.Cells">
   <cell-element handler="{{cell.handler}}"/>
   <!-- cell.handler is e.g. "User" -->
</p>

myapp.directive('cellElement', function() {
  return {

    restrict: 'E',       

    templateUrl: function (tElement, tAttrs, $compile) {
      return '/ajax/' + tAttrs.handler == undefined ? 'foo' : tAttrs.handler +'.html';
    },       
 }
 });

不幸的是,tAttrs.handler 的值始终是文字表达式“{{cell.handler}}”,而不是相应的值。我尝试了很多不同的方法 - 你猜到了吗?

更新:

myapp.directive('cellElement', function() {
return {        
   restrict: 'E',
   scope: { handler: '=handler' },
   template: '<ng-include src="\'/ajax/\' + handler"></ng-include>'    
}
}); 

作为解决方法,我使用了另一种可行的方法。但我更喜欢使用 templateUrl 函数的初始方式,例如想检查“handler”是否是一个有效值。

【问题讨论】:

  • 试试不带大括号的handler="cell.handler"
  • 已经试过了,不行。仍然是相同的字面值。

标签: javascript angularjs angularjs-directive


【解决方案1】:

我认为这个替代方案可行:

myapp.directive('cellElement', function() {
  return {
    restrict: 'E',       
    template: '<div data-ng-include="templateUrl"></div>',
    link: function ($scope, iElement, attr) {
        $scope.templateUrl= $scope[attr.handler];
    }

 }

而且你必须在没有支持的情况下进行消费:

<p ng:repeat="cell in field.Cells">
   <cell-element handler="cell.handler"/>
   <!-- cell.handler is e.g. "User" -->
</p>

【讨论】:

    【解决方案2】:

    问题是模板可能没有被编译,所以你想要的值还没有被插值。如果您尝试在链接函数中检索它,它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      相关资源
      最近更新 更多