In the realm of directives, there exist two powerful entities known as collection
and element
. Both have the ability to transclude their content and both default to having scope: false
.
These directives serve as wrappers for containers and items within those containers. Here is a typical usage example:
<body ng-app="myApp" ng-controller="MyController">
<collection>
<element>inner1</element>
<element>inner2</element>
<element>inner3</element>
</collection>
</body>
To define these directives in AngularJS, you can use the following code:
angular.module('myApp', [])
.controller('MyController', function($scope){
console.log('MyController', $scope.$id);
})
.directive('collection', function($compile){
return {
transclude: 'true',
restrict: 'E',
template: '<header>header</header><div><ul ng-transclude></ul></div><footer>footer</footer>',
link: function(scope){
console.log('collection', scope.$id);
}
}
})
.directive('element', function(){
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<li><div ng-transclude></div></li>',
link: function(scope){
console.log('element', scope.$id);
}
}
});
The issue at hand arises from the fact that the element
directive does not share the same scope as the collection
directive, and the reason behind this discrepancy remains elusive.
Here's the console output for reference:
MyController 003
element 004
element 004
element 004
collection 003
It is evident from the output that while MyController
shares scope #3 with collection
, all instances of element
utilize scope #4.
For a functioning example, please check out this Plunkr.