Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
Shivkumar Avatar asked Aug 27 '13 12:08

Shivkumar


People also ask

What is shared scope in AngularJS?

Shared scope: directive and controllers share the scope and the data. We cannot pass data explicitly to the directive. 2. Inherited scope: directive inherits the scope of the controller.

What is Link function in AngularJS directive?

link function is basically used to manipulate the DOM( Document Object Model ) element using custom directive. link option in custom directive registers DOM listener and also update the DOM. Watch the live demo or download code from the link given below.

How does scope inheritance work in AngularJS?

Scope InheritanceIf we define nested controllers, then the child controller inherits the scope of its parent controller. We assign values to the models in shapeController. We override message in child controller named circleController.

What does $compile do in AngularJS?

The $compile service is the service to use for compilation. Invoking $compile against markup will produce a function you can use to bind the markup against a particular scope (what Angular calls a linking function). After linking, you'll have DOM elements you can place into the browser.


1 Answers

AngularJS supports directive controllers, which are controllers that are shared between multiple directives that require the same controller. This allows you to access and modify tableConfig in any directive that requires that controller, without having to declare a separate service or event. For more information, look at "Creating Directives that Communicate" in the directives documentation.

This is how ngModel and ngForm work, for example.

like image 136
Steve Klösters Avatar answered Oct 05 '22 03:10

Steve Klösters