文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
transclude 的细节
18.6. transclude的细节
transclude
有两方面的东西,一个是使用 $compile
时传入的函数,另一个是定义指令的 compile
函数时接受的一个参数。虽然这里的一出一进本来是相互对应的,但是实际使用中,因为大部分时候不会手动调用 $compile
,所以,在“默认”情况下,指令接受的 transclude
又会是一个比较特殊的函数。
看一个基本的例子:
var app = angular.module('Demo', [], angular.noop); app.directive('more', function(){ var func = function(element, attrs, transclude){ var sum = transclude(1, 2); console.log(sum); console.log(element); } return {compile: func, restrict: 'E'}; }); app.controller('TestCtrl', function($scope, $compile, $element){ var s = '<more>123</more>'; var link = $compile(s, function(a, b){return a + b}); var node = link($scope); $element.append(node); }); angular.bootstrap(document, ['Demo']);
我们定义了一个 more
指令,它的 compile
函数的第三个参数,就是我们手工 $compile
时传入的。
如果不是手工 $compile
,而是 ng 初始化时找出的指令,则 transclude
是一个 link
函数(指令定义需要设置 transclude
选项):
<div more>123</div>
app.directive('more', function($rootScope, $document){ var func = function(element, attrs, link){ var node = link($rootScope); node.removeAttr('more'); //不去掉就变死循环了 $('body', $document).append(node); } return {compile: func, transclude: 'element', // element是节点没,其它值是节点的内容没 restrict: 'A'}; });
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论