AngularJS指令属性多个用法

时间:2018-06-04 11:42:29

标签: javascript angularjs directive

我有以下HTML:

<my-dom attri="something 01">content 01</my-dom>
<my-dom attri="something 02">content 02</my-dom>
<my-dom attri="something 03">content 03</my-dom>

现在我希望在运行时将其替换为:

<div>something 01: content 01</div>
<div>something 02: content 02</div>
<div>something 03: content 03</div>

因此我创建了这个AngularJS指令:

app.directive('myDom', function() {
    var content;

    return {
        restrict: 'EA',
        replace: true,

        scope : true,
        // scope : false,
        // scope: {},

        template: function(elem, attr){
            content = elem.clone();
            return '<div>{{myContent}}: {{oldContent}}</div>';
        },

        controller: function(){
        },
        link: {
            pre: function(scope, elem, attr){
                scope.myContent = content.attr("attri"); // could also use "attr"
                scope.oldContent= content.html(); // could not use "elem" or "attr"
            },
            post: function(scope, elem, attr){
            },
        }
    };
});

这里我首先克隆私有变量“content”中的originale DOM元素,然后用新的元素替换DOM元素。在这个新的HTML标签中,我插入旧代码中的属性数据。但在这里它变得混乱:

输出代码为:

<div>something 03: content 03</div>
<div>something 03: content 03</div>
<div>something 03: content 03</div>

因此范围有问题。但是什么呢? 从文档中,scope : true通过继承父作用域来为指令创建新作用域 父作用域的更改确实会影响指令作用域,但指令作用域中的更改不会更改父作用域。

我唯一可以想象的是:
这一个指令只有一个范围。所以<my-dom>的所有三种用法都有一个相同的范围 那是对的吗?我怎样才能得到我想要的结果?

1 个答案:

答案 0 :(得分:2)

正如我在评论中提到的,您的<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script> <body ng-app="plunker"> <div ng-controller="MainCtrl"> <my-dom attri="something 01">content 01</my-dom> <my-dom attri="something 02">content 02</my-dom> <my-dom attri="something 03">content 03</my-dom> </div> </body>在所有指令实例之间共享,因此在每个模板函数中都会被覆盖。

要实现所需的行为,您可以使用transcludeFn together with transclude: true访问包含在您的指令中的元素,请参阅下面的示例:

&#13;
&#13;
{{1}}
&#13;
{{1}}
&#13;
&#13;
&#13;

this SO question中的一些更有趣的答案和示例。