ng-transclude替换内容而不是追加

时间:2014-03-02 20:17:12

标签: javascript angularjs

我正在学习AngularJS。

我浏览了这个video,这里显示了将ng-transclude放在指令模板中的标记上,会在此标记中附加已存在的DOM内容。

代码:

<html ng-app="myApp">
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body ng-controller="AppCtrl">
    <panel>
        <button>Click Me</button>
    </panel>

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
    <script>
            var app = angular.module('myApp', []);
            app.controller('AppCtrl', function() {

            });
            app.directive('panel', function() {        //can return a function (link) or an object
                return {
                    restrict: 'E',
                    transclude: true,
                    template: '<span> This is my custom span</span><div class="panel" ng-transclude>this is my div</div><span>Another span follows</span>'
                }
            });
    </script>
</body>
</html>

这是fiddle,证明了这个问题。

2 个答案:

答案 0 :(得分:2)

这是最新版本的正常行为。

来自Angular API on ng-transclude

"Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted."

如果你使用Angular版本1.0.8运行你的小提琴,那么它将像在视频中一样工作。

答案 1 :(得分:0)

使用<span>作为翻译主机:

// Assign tpl var to template configuration property
var tpl = [
        '<span> This is my custom span</span>',
        '<div class="panel">',
            '<span ng-transclude></span>',
            ' this is my div',
        '</div>',
        '<span ng-switch-when="divider"></span>',
        '<span>Another span follows</span>'', // End
    ].join('\n');