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

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

发布时间:2020-12-17 17:38:56 所属栏目:安全 来源:网络整理
导读:我正在为客户可以使用的库创建指令.我需要让客户为指令创建自己的模板,并将该模板的绝对url值传递给我的指令.我的一个指令将在其中包含另一个自定义指令,并且它的模板将根据父指令的一个属性的值来计算.这是一个例子: parent-dir menu-template="this.html"
我正在为客户可以使用的库创建指令.我需要让客户为指令创建自己的模板,并将该模板的绝对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);
    })

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

(编辑:李大同)

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

    推荐文章
      热点阅读