directive的transclude是做什么的呢?
英文原文的解释是:
transclude
makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.
意思是transclude可以使directive的内容可以访问外部的scope,而不是内部。
什么时候用transclude?
英文原文:
Best Practice: only use
transclude: true
when you want to create a directive that wraps arbitrary content.
意思是当directive需要包含其他的零散的内容时,需要设置transclude:true。
还是看代码,比较好懂:
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
<script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script>
</head>
<body>
<div ng-controller="ctrl1">
<div my-directive>
我的数据是:{{myData}}
</div>
ctrl1中我的数据是: {{myData}}
</div>
<script>
var app = angular.module('app', []);
app.directive('myDirective', [function() {
return {
replace: false,
transclude: true,
template: '<div><h1 ng-transclude></h1></div>',
scope:{},
link: function(scope) {
scope.myData = "directive data";
}
}
}])
app.controller('ctrl1', ['$scope', function($scope) {
$scope.myData = 'ctrl data';
}])
</script>
</body>
</html>
运行结果:
虽然directive中myData值为 directive data,但是实际显示的是 ctrl1里的myData.
需要注意的是:directive包含的内容会放在ng-transclude标示的元素中,transclude要配合ng-transclude使用。我们写一些dialog会经常用到这个属性。
另外,可以使用$transclude和transcludeFn来控制使用哪些外部scope的一些属性,而不是整个外部scope.有兴趣的可以私下探讨。