将父指令属性传递给子指令属性

Mic*_*ely 5 angularjs angularjs-directive angularjs-scope

我正在为客户可以使用的库创建指令.我需要让客户为指令创建自己的模板,并将该模板的绝对url值传递给我的指令.我的一个指令将在其中包含另一个自定义指令,并且它的模板将根据父指令的一个属性的值来计算.这是一个例子:

<parent-dir menu-template="this.html" item-template="that.html"></parent-dir>
Run Code Online (Sandbox Code Playgroud)

我有一个这个指令的模板,如下所示:

<ul style="list: none" ng-repeat="item in menu">
    <child-dir template="{{itemTemplate}}"></child-dir>
</ul>
Run Code Online (Sandbox Code Playgroud)

我的指令看起来像这样:

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',
        templateUrl: function (element, attrs) {
            alert('Item Template: ' + attrs.template);
            return attrs.template;
        },
        controller: function ($scope, $element, $attrs) {                
            $scope.job;
            alert('Under job: ' + $scope.itemTemplate);
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

我没有显示所有代码,但这是我的问题的主要部分.当我运行它时,我继续为childDir上的模板定义未定义.

从parentDir延续itemTemplate值的最佳实践是什么,以便childDir可以将它作为模板使用?

Ed *_*ffe 5

您遇到问题的原因是因为生成函数的函数在分配给指令templateUrl之前正在运行scope- 必须在替换插值数据之前完成.

换句话说:在templateUrl函数运行时,template属性的值仍然是"{{itemTemplate}}".在指令的链接(preLink准确地说)功能运行之前,情况仍将如此.

我创建了一个plunker来演示点这里.务必打开控制台.您将看到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);
    })
Run Code Online (Sandbox Code Playgroud)

然后,您可以删除template对指令定义对象中的任何引用,并且一旦插入了属性,这将安全地运行.

  • 用例略有不同,但基本问题相同。这个答案很有效。@Michael,如果你在附近,你认为值得接受这个答案来帮助像我这样的其他人,表明这是一个很好的答案吗? (2认同)