angularjs - 如何通过属性中的作用域变量传递templateUrl

标签 angularjs

我正在尝试通过作用域变量传递模板的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", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) {
        return {
            scope: {
                template: '@template'
            },
            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", ["$compile", '$http', '$templateCache', '$parse', function ($compile, $http, $templateCache, $parse) {
        return {
            restrict: 'A',
            link: function(scope , element, 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));                
                    });    
              }
            } 
        }
    }]);

这是一个工作的柱塞:http://plnkr.co/edit/n20Sxq?p=preview

关于angularjs - 如何通过属性中的作用域变量传递templateUrl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19501584/

相关文章:

angularjs - nggrid 单元格模板中的 ui-date-format

javascript - 为什么一个 Angular 表达式正在评估类,但没有检查?

javascript - 具有 2 个条件的 NG-grid 过滤器

javascript - 数组过滤器为空时返回全部

angularjs - 通过 AngularJS 中的服务将数据加载到 Controller 中的方法

angularjs laravel 页面刷新出现 404 错误

html - 使用angularjs检查字符串是否包含http url

javascript - 为什么我的 EventListener 被调用两次?

javascript - 在嵌套指令场景中从内部指令(模板内部)传递属性

angularjs - 如何在 Angularjs $http.post 中传递参数