Wednesday, 5 November 2014

Transclude explained

Combination of transfer and include, this simply means you want to take the HTML within the usage of your directive and include it within the template supplied by your directive definition.

image

The key lines are 14, 18 and 30.  These tell Angular I want to transfer the contents of the HTML DOM and here is where I want to include it.  Line 30 is the usage of the directive including the {{text}} which is transcluded.

 

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Transclude</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
</head>
<body ng-app="transcludeExample">
<script>
angular.module('transcludeExample', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div>' +
'<h1>{{title}}</h1>' +
'<ng-transclude></ng-transclude>' +
'</div>'
};
})
.controller('ExampleController', ['$scope', function($scope) {
$scope.title = 'Transfer and Include';
$scope.text = 'Takes the HTML within your directive and includes it in your directive template';
}]);
</script>
<div ng-controller="ExampleController">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</body>
</html>
view raw transclude hosted with ❤ by GitHub

 

image

No comments:

Post a Comment