var myApp = angular.module('myApp', [])
.controller('MyCtrl', function ($scope) {
$scope.user = {
name: "Jimmy",
title: "The Man",
roles: ["Guy with keyboard", "Stapler-holder"]
};
})
.directive('userProfile', function () {
return {
restrict: 'E',
transclude: true,
scope: {
entity: '=',
},
// If you specify content within this directive it will be transcluded, replacing the
// contents of this template
template: '<div>' +
' <label>Name:</label>{{ entity.name }}<br>' +
' <label>Title:</label>{{ entity.title }}<br>' +
' <label>Roles:</label>' +
' <ul>' +
' <li ng-repeat="role in entity.roles">{{ role }}</li>' +
' </ul>' +
'</div>',
link: function (scope, element, attrs, ctrl, transcludeFn) {
transcludeFn(scope, function cloneFn(cElement) {
if (cElement.length) {
element.empty();
element.append(cElement);
}
});
}
}
});
<div ng-controller="MyCtrl">
<user-profile entity="user"></user-profile>
<br>
<user-profile entity="user">
<div>Custom content!</div>
The user's name is {{ entity.name }}<br>
His title is {{ user.title || "unknown because it's an isolate scope"}}<br>
However, we can use $parent to access the scope outside of the directive: {{ $parent.user.title }}
</user-profile>
</div>
label {
margin: 0 0.5em 1em;
width: 60px;
text-align: right;
display: inline-block;
}
ul, pre {
display: inline-block;
}
External resources loaded into this fiddle: