Transclude指令无法修改内容

时间:2015-05-31 14:21:44

标签: angularjs angularjs-directive

我已经在AngularJs 1.3中将transclude指令定义为beliw - 但它似乎对渲染没有任何影响。
链接阶段的日志语句显示虽然调用了该指令。

的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指令的工作原理吗?

1 个答案:

答案 0 :(得分: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');}
    }
});

正如评论中所提到的,第二个例子可以让你更好地理解实际发生的事情。

相关问题