我有两个带隔离范围的指令。是否可以使用绑定在两者之间传递信息?
无论是否进行转换,数据视图B中的parentSq始终未定义。
由于
HTML:
<dataview-a parent-sq="rootStudioQuery">
<dataview-b parent-sq="dataViewAStudioQuery">
</dataview-b>
</dataview-a>
指令:
app.directive('dataviewA', function () {
return {
restrict: 'E',
scope:{
parentSq:"="
},
controller:function($scope){
debugger;
$scope.dataViewAStudioQuery = {
filters:[]
};
}
}
});
app.directive('dataviewB', function () {
return {
restrict: 'E',
scope:{
parentSq:"="
},
transclude:true,
link:function(scope,e,a){
//scope.parentSq is always undefined
}
}
});
答案 0 :(得分:1)
这是一个解决方案:
基本上,您缺少父指令中的输出对象。我添加了outputObject:&#34; =&#34;到父指令的范围:
scope:{
parentSq:"=",
outputObject: "="
}
并修改了child指令以观察parentSq:
scope.$watch('parentSq', function(oldVal,newVal){
console.log(scope.parentSq);
});
并像这样修改HTML(传递输出对象):
<dataview-a parent-sq="rootStudioQuery" output-object='dataViewAStudioQuery'>
<dataview-b parent-sq="dataViewAStudioQuery">
</dataview-b>
</dataview-a>
https://plnkr.co/edit/jxzw18kZwkk3YSgV2f3A?p=preview
app.directive('dataviewA', function () {
return {
restrict: 'E',
scope:{
parentSq:"=",
outputObject: "="
},
controller:function($scope){
$scope.outputObject = {
filters:[]
};
}
}
});
app.directive('dataviewB', function () {
return {
restrict: 'E',
scope:{
parentSq:"="
},
transclude:true,
link:function(scope,e,a){
scope.$watch('parentSq', function(oldVal,newVal){
console.log(scope.parentSq);
});
//scope.parentSq is always undefined
}
}
- 使用广播/ $ rootScope的旧答案 -
$ rootScope。$ broadcast或$ rootScope。$ emit怎么样?如果您不需要在$ rootScope下面广播到子范围,请使用$ emit。
$rootScope.$broadcast('something', {
//data object here
example: 'Example Data'
});
$rootScope.$emit('something', {
//data object here
example: 'Example Data'
});
收听
$rootScope.$on('something', function (event, data) {
// data has example: 'Example Data' within
});
参考:https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope