Shivkumar Shivkumar - 6 months ago 23
AngularJS Question

How do I share scope between two directives in AngularJS?

I want to share the

$scope
between the following two directives:

One23SRCApp.directive('directive1',function() {
return {
restrict: "A",
scope:true,
link: function (scope, element, attrs) {
scope.tablename = "table";
}
};
});


One23SRCApp.directive('directive2',function() {
return {
restrict: "A",
link: function (scope, element, attrs) {
var tablename = scope.tablename;
}
};
})


In the HTML, I have:

<input type="text" directive2 placeholder="Search Models...">

<table directive1>
<tr>
<td>column1</td>
<td>column1</td>
</tr>
</table>


I have created the directive named "directive1" with isolated scope, assigning the name "table" to the
scope.tablename
property. I am not able access this scope property in the other directive.

So how can I access the scope of one directive in another?

Answer

You can do a $rootScope.$broadcast on items that you need to sync across directive.

Or you can pass a object to your directive1 isolated scope, which would act as a communication mechanism. On this object if you change sub property like tablename, that would affect in the parent scope.

Something like

One23SRCApp.directive('directive1',function() {
    return {
        restrict: "A",
        scope:{tableconfig:'='},
        link: function (scope, element, attrs) {
           scope.tableconfig.tablename= "table";
        }
    };
});


One23SRCApp.directive('directive2',function() {
    return {
        restrict: "A",
           link: function (scope, element, attrs) {
           var tablename = scope.tableconfig.tablename;
        }
    };
})

The HTML becomes

<table directive1 tableconfig='tableconfig'>
  <tr>
     <td>column1</td>
   <td>column1</td>
   </tr>
</table>

Your controller should have this object defined

$scope.tableconfig={};