参考
参考plunker:http ://plnkr.co/edit/otv5mVVQ36iPi3Mp0FYw?p=preview
问题说明
假设我们有两个指令,first-directive
并且second-directive
. 现在假设我们只能访问first-directive
我们希望包装second-directive
的对象,并将我们自己的操作属性传递给它。
app.directive('firstDirective', function() {
return {
scope: true,
priority: 1000,
transclude: true,
template: function(element,attributes){
console.log('template')
return '<second-directive two="{{one}}"></second-directive>'
},
compile: function(element,attributes) {
console.log('compile')
return {
pre: function(scope){
scope.one = 'foo'
console.log('cpre')
},
post: function(scope){
scope.one = 'foo'
console.log('cpost')
},
}
},
controller: ['$scope','$attrs',function($scope,$attrs){
console.log('controller');
$scope.one = 'foo';
}],
}
})
app.directive('secondDirective',function(){
return {
template: function (element,attributes){
console.log(attributes.two) //{{one}} not 'foo' or 'test'
return 'Hello {{two}}'
}
}
});
first-directive
被称为如下:
<first-directive one='test'></first-directive>
console.log 输出如下:
template
compile
{{one}}
controller
cpre
cpost
所以从这里我了解到模板是在编译之前调用的。这在我的新手眼中很奇怪,因为无论如何都无法通过编译、控制器、前置或后置链接来操纵模板函数传回的值!
问题是这样的:
如何second-directive
使用我想要的动态属性值调用 ?请记住,这second-directive
是完全独立的,我们不能在那里添加代码。
PS - 我有一个可能的想法是调用第二个指令如下:
template: function(element,attributes){
console.log('template')
var explicit = ???? /* how to access scope? */
return '<second-directive two="'+ explicit +'"></second-directive>'
},
或者
template: function(element,attributes){
console.log('template')
return $interpolate('<second-directive two="{{one}}"></second-directive>')(scopeObj) /* how does one access scopeObj with current scope values here? */
},
然而,再一次,我不确定如何在调用任何其他函数之前将值传递给第一指令。控制器可以访问 $scope,它被称为 AFTER 模板。
非常感谢您的建议。