我在 angularjs 中编写了两个指令,一个嵌入到另一个中。
以下是指令的脚本:
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);
}
};
}
]);
下面是一段html:
<foo ng-controller="IndexController">
<bar></bar>
</foo>
下面是生成的元素,通过 chrome 开发者工具检查
<div id="test" ng-transclude="" ng-controller="IndexController" class="ng-scope">
<div ng-transclude="" class="ng-scope"></div>
</div>
下面是 chrome 控制台输出:
test2
Array[0]
length: 0
__proto__: Array[0]
angular.js:5930
test1
Array[0]
length: 0
__proto__: Array[0]
问题:子指令无法获取父指令的控制器,因此“bar”链接函数的第四个参数“fooCtrl”是一个空数组。我做错了什么?
更新并回答:
最后我找到了造成奇怪结果的原因。这只是我犯的一个愚蠢的错误:
// in directive "foo"
controller: function($scope) {
this.scope = $scope;
// This line below is wrong. It is here
// because I transcompiled coffeescript to js.
// return $scope.panes = [];
// It should be like below:
$scope.panes = []
// I should have written .coffee like below
// controller: ($scope) ->
// @scope = $scope
// $scope.panes = []
// return # prevent coffeescript returning the above expressions.
// # I should rather have added the above line
}
纠正错误后,我尝试发现没有什么可以阻止使用控制器或在子指令中提供空内容。