简体   繁体   English

如何在Angular中渲染页面后将指令作为属性添加到页面?

[英]How to add directive as attribute to page after page is rendered in Angular?

I have an html like this 我有一个这样的HTML

    <myCustomTag>           
        <img ng-repeat="i in [1,2,3,4,5]" ng-src="./resource/image/ball/ball_{{i}}.png">
    </myCustomTag>

Also i have an attribute type directive that adds some feature to the tag (lets call it myFeature attribute). 我也有一个属性类型指令,它向标记添加了一些功能(我们称其为myFeature属性)。

In myCustomTag directive i want to add myFeature attribure to all children nodes. 在myCustomTag指令中,我想将myFeature属性添加到所有子节点。 I need to wait page to be rendered first in order to get children tags of myCustomTag (because of ngRepeat) as follows: 我需要等待页面首先被渲染才能获取myCustomTag的子标签(由于ngRepeat),如下所示:

    app.directive('my-custom-tag', function(){
        return {
            restrict: 'E',
            link: function(scope, element, attributes) {
                element.ready(function(){
                    var nodes = element.children();
                    for(var i=0; i<nodes.length; ++i){
                        angular.element(nodes[i]).attr('my-feature','');
                    }
                });
            }
        };
    }); 

The problem is my feature directive is not applied to child nodes. 问题是我的功能指令不适用于子节点。 Actually it is added as attribute but noting more. 实际上,它是作为属性添加的,但要注意更多。 I think it is not working since i add attribute after evaluation of the tag by angular, but also i think there should be a way to do this. 我认为这是行不通的,因为我在按角度对标签进行评估后添加了属性,但我也认为应该有一种方法。 Any idea? 任何想法?

If you plan on modifying your directive's children, then the perfect place to do this is in your compile function : 如果您打算修改指令的子代,那么执行此操作的最佳位置是在您的编译函数中:

app.directive('my-custom-tag', function(){
    return {
        restrict: 'E',
        compile: function(element, attributes) {
              var nodes = element.children();
              for(var i=0; i<nodes.length; ++i){
                  angular.element(nodes[i]).attr('my-feature','');
              }
        }
    };
}); 

When Angular walks the DOM tree, the children of your directive have not been compiled (or linked) yet. 当Angular遍历DOM树时,指令的子级尚未被编译(或链接)。 By modifying the DOM here, you don't have to worry about doing anything special outside of the Angular compile/link process. 通过在此处修改DOM,您不必担心在Angular编译/链接过程之外进行任何特殊操作。

Angular directives' behavior cannot be interpreted by the browser without Angular's compile step. 如果没有Angular的编译步骤,浏览器将无法解释Angular指令的行为。 I would suggest you use ng-template with the $compile service and then append these compiled elements to the DOM 我建议您将ng-template与$ compile服务一起使用,然后将这些已编译的元素附加到DOM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM