W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
transclude 有兩方面的東西,一個(gè)是使用 $compile 時(shí)傳入的函數(shù),另一個(gè)是定義指令的 compile 函數(shù)時(shí)接受的一個(gè)參數(shù)。雖然這里的一出一進(jìn)本來(lái)是相互對(duì)應(yīng)的,但是實(shí)際使用中,因?yàn)榇蟛糠謺r(shí)候不會(huì)手動(dòng)調(diào)用 $compile ,所以,在“默認(rèn)”情況下,指令接受的 transclude 又會(huì)是一個(gè)比較特殊的函數(shù)。
看一個(gè)基本的例子:
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']);
我們定義了一個(gè) more 指令,它的 compile 函數(shù)的第三個(gè)參數(shù),就是我們手工 $compile 時(shí)傳入的。
如果不是手工 $compile ,而是 ng 初始化時(shí)找出的指令,則 transclude 是一個(gè) link 函數(shù)(指令定義需要設(shè)置 transclude 選項(xiàng)):
<div more>123</div>
app.directive('more', function($rootScope, $document){ var func = function(element, attrs, link){ var node = link($rootScope); node.removeAttr('more'); //不去掉就變死循環(huán)了 $('body', $document).append(node); } return {compile: func, transclude: 'element', // element是節(jié)點(diǎn)沒(méi),其它值是節(jié)點(diǎn)的內(nèi)容沒(méi) restrict: 'A'}; });
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: