A couple of angularjs directives were written, with one being nested inside the other.
Here are the scripts for the directives:
module.directive('foo', [
'$log', function($log) {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<div id="test" ng-transclude></div>',
controller: function($scope) {
this.scope = $scope;
return $scope.panes = [];
},
link: function(scope, element, attrs) {
return $log.log('test1', scope.panes);
}
};
}
]);
module.directive('bar', [
'$log', function($log) {
return {
restrict: 'E',
replace: true,
transclude: true,
require: '^?foo',
controller: function($scope) {
return this.x = 1;
},
template: '<div ng-transclude></div>',
link: function(scope, element, attrs, fooCtrl) {
return $log.log('test2', fooCtrl);
}
};
}
]);
Below is a snippet of html:
<foo ng-controller="IndexController">
<bar></bar>
</foo>
The generated element was inspected using Chrome developer tools:
<div id="test" ng-transclude="" ng-controller="IndexController" class="ng-scope">
<div ng-transclude="" class="ng-scope"></div>
</div>
Chrome console output:
test2
Array[0]
length: 0
__proto__: Array[0]
angular.js:5930
test1
Array[0]
length: 0
__proto__: Array[0]
Question: The child directive is unable to access the parent directive's controller, resulting in the fourth parameter "fooCtrl" in the link function of "bar" being an empty array. What mistake have I made?
Update and Answer:
After further investigation, I discovered a simple error that caused the unexpected outcome:
// in directive "foo"
controller: function($scope) {
this.scope = $scope;
// The following line is incorrect. It was included
// due to transcompiling from coffeescript to js.
// return $scope.panes = [];
// It should be revised as follows:
$scope.panes = []
// The .coffee script should appear like below
// controller: ($scope) ->
// @scope = $scope
// $scope.panes = []
// return # prevent coffeescript returning the above expressions.
// # I should rather have added the above line
}
After correcting this mistake, it was verified that there are no obstacles in utilizing controllers or providing data in child directives.