我正在为客户可以使用的库创建指令.我需要让客户为指令创建自己的模板,并将该模板的绝对url值传递给我的指令.我的一个指令将在其中包含另一个自定义指令,并且它的模板将根据父指令的一个属性的值来计算.这是一个例子:
<parent-dir menu-template="this.html" item-template="that.html"></parent-dir>
我有一个这个指令的模板,如下所示:
<ul style="list: none" ng-repeat="item in menu"> <child-dir template="{{itemTemplate}}"></child-dir> </ul>
我的指令看起来像这样:
angular.module('myApp') .directive('parentDir',function () { return { restrict: 'E',scope: { menuTemplate: '@',itemTemplate: '@',menuType: '@',menuName: '@',menuId: '@',},templateUrl: function (element,attrs) { alert('Scope: ' + attrs.menuTemplate); return attrs.menuTemplate; },controller: function ($scope,$element,$attrs) { $scope.defaultSubmit = false; alert('Menu: '+$attrs.menuTemplate); alert('Item: ' + $attrs.itemTemplate); $scope.itemTemplate = $attrs.itemTemplate; if ($attrs.$attr.hasOwnProperty('defaultSubmit')) { alert('It does'); $scope.defaultSubmit = true; } } }; }) .directive('childDir',function () { return { restrict: 'E',require: '^parentDir',attrs) { alert('Item Template: ' + attrs.template); return attrs.template; },$attrs) { $scope.job; alert('Under job: ' + $scope.itemTemplate); } }; });
我没有显示所有代码,但这是我的问题的主要部分.当我运行它时,我继续为childDir上的模板定义未定义.
从parentDir延续itemTemplate值的最佳实践是什么,以便childDir可以将它作为模板使用?
解决方法
您遇到问题的原因是因为生成templateUrl的函数在将作用域分配给指令之前正在运行 – 必须在替换插值数据之前完成.
换句话说:在templateUrl函数运行时,template属性的值仍为“{{itemTemplate}}”.在指令的链接(preLink精确)功能运行之前,情况仍然如此.
我创建了一个plunker来演示here点.确保打开控制台.您将看到templateUrl在父链接函数和子链接函数之前运行.
那你做什么呢?
幸运的是,angular提供了一个$templateRequest服务,它允许您以与使用templateUrl相同的方式请求模板(它还使用了方便的$templateCache).
$templateRequest(attrs.template) .then(function (tplString){ // compile the template then link the result with the scope. contents = $compile(tplString)(scope); // Insert the compiled,linked element into the DOM elem.append(contents); })