【问题标题】:Transclude directive fails to modify contentTransclude 指令无法修改内容
【发布时间】:2015-05-31 14:21:44
【问题描述】:

我在 AngularJs 1.3 中定义了一个 transclude 指令,但它似乎对渲染没有任何影响。
链接阶段的日志语句显示该指令已被调用。

index.html

<html lang="en" ng-app="directivesApp">
<head>
    <script src="js/angular.min.js"></script>
    <script src="js/app.js"></script>
 </head>
<body ng-controller="directiveCtrl">
    <label>Geography</label><input type="text" ng-model="geography"/>
    <br>
    <div transclude-demo>
    <button ng-click='showGeography()'>Show Geography</button>
    <a href="#">and a link</a>
    </div>
</body>
</html>

app.js

angular.module('directivesApp', [])
.controller('directiveCtrl',function($scope){
    $scope.showGeography=function(){alert('I am here');}
})
.directive('transcludeDemo',function(){
    return{
        transclude: true,
        template: '<div ng-transclude> This is my directive content</div>',
        link:function ($scope, element, attrs) { console.log('invoked in scope');}
    }
});

我本来希望 transclude 指令用其模板的内容替换/修改 div 的内容。
但是,我发现 div 是按原样呈现的。

transclude 指令是这样工作的吗?

【问题讨论】:

  • 您应该看到按钮和链接呈现,而不是文本 "This is my directive content"ng-transclude 将其元素的内容替换为嵌入的内容
  • 为了更好的测试,将你的指令模板替换为&lt;div&gt;&lt;div ng-transclude&gt;&lt;/div&gt;&lt;div&gt;This is my directive content&lt;/div&gt;&lt;/div&gt;

标签: angularjs angularjs-directive


【解决方案1】:

Transclude 用于保留已经存在的内容,因此如果您只想替换内容,您真正需要的只是模板。您在示例中看不到太多内容,因为您包含的 div 基本相同。

替换内容:

.directive('transcludeDemo',function(){
    return{
        template: '<div>This is my directive content</div>',
        link:function ($scope, element, attrs) { console.log('invoked in scope');}
    }
});

如果您想以某种方式组合新/旧内容,请在模板中添加 ng-transclude 之外的内容,它将组合呈现。

与 transclude 结合:

.directive('transcludeDemo',function(){
    return{
        transclude: true,
        template: '<div>' +
                     '<p>This text will stay in tact</p>' +
                     '<div ng-transclude>This text will be replaced</div>' +
                  '</div>',
        link:function ($scope, element, attrs) { console.log('invoked in scope');}
    }
});

正如 cmets 中所述,第二个示例应该让您更好地了解实际发生的情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    相关资源
    最近更新 更多