user714157 user714157 - 6 months ago 22
AngularJS Question

Binding Between Two Isolated Scopes

I have two directives with isolated scopes. Is it possible to pass information between the two using binding?

With or without transclusion, parentSq in data view B is always undefined.

Thanks

HTML:

<dataview-a parent-sq="rootStudioQuery">
<dataview-b parent-sq="dataViewAStudioQuery">
</dataview-b>
</dataview-a>


Directives:

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
}
}
});

Answer

Here is a solution:

Basically, you are missing an output object from the parent directive. I have added outputObject: "=" to the scope of the parent directive:

scope:{
  parentSq:"=",
  outputObject: "="
}

And modified the child directive to watch parentSq:

      scope.$watch('parentSq', function(oldVal,newVal){

        console.log(scope.parentSq);

      });

And modified the HTML like so (to pass output object):

<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
    }
}

-- Old Answer using broadcasts / $rootScope --

How about $rootScope.$broadcast, or $rootScope.$emit? Use $emit if you do not need to broadcast below the $rootScope to child scopes.

$rootScope.$broadcast('something', {
  //data object here
  example: 'Example Data'
});

$rootScope.$emit('something', {
  //data object here
  example: 'Example Data'
});

Listen with

$rootScope.$on('something', function (event, data) {
    // data has example: 'Example Data' within
});

Reference: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Comments