加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何通过属性中的范围变量传递templateUrl

发布时间:2020-12-17 07:34:36 所属栏目:安全 来源:网络整理
导读:我正在尝试通过范围变量传递模板的URL.范围不会更改,因此模板不需要基于它进行更新,但是当前范围变量始终未定义. div cell-item template="{{col.CellTemplate}}"/div 理想情况下,指令将是: .directive("cellItem",["$compile",'$http','$templateCache','$
我正在尝试通过范围变量传递模板的URL.范围不会更改,因此模板不需要基于它进行更新,但是当前范围变量始终未定义.
<div cell-item template="{{col.CellTemplate}}"></div>

理想情况下,指令将是:

.directive("cellItem",["$compile",'$http','$templateCache','$parse',function ($compile,$http,$templateCache,$parse) {
        return {
            scope: {
                template: '@template'
            },templateUrl: template // or {{template}} - either way
        };
    }])

但是,这不起作用.我已经尝试了许多不同的排列来完成相同的概念,这似乎是最接近的,但它仍然不起作用.

.directive("cellItem",link: function (scope,element,attrs) {
                var templateUrl = $parse(attrs.template)(scope);
                $http.get(templateUrl,{ cache: $templateCache }).success(function (tplContent) {
                    element.replaceWith($compile(tplContent)(scope));
                });
            }
        };
    }])

我也尝试过使用ng-include,但在编译之前也没有评估范围变量. CellTemplate值来自数据库调用,因此在评估之前完全未知.任何有关此工作的建议将不胜感激!

编辑:
我正在使用angular 1.0.8并且无法升级到更新版本.

你离我不远.

您不需要为指令使用隔离范围.您可以像这样传递templateUrl:

<div cell-item template="col.CellTemplate"></div>

然后添加一个监视以检测模板值何时更改:

.directive("cellItem",$parse) {
        return {
            restrict: 'A',link: function(scope,attrs) {

              scope.$watch(attrs.template,function (value) {
                if (value) {
                  loadTemplate(value);
                }
              });

              function loadTemplate(template) {
                  $http.get(template,{ cache: $templateCache })
                    .success(function(templateContent) {
                      element.replaceWith($compile(templateContent)(scope));                
                    });    
              }
            } 
        }
    }]);

这是一个有效的Plunker:http://plnkr.co/edit/n20Sxq?p=preview

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读