Rock
Rock

Reputation: 336

how to pass argument from directive to directive

I have two directive and I want to pass argument from one directive to another directive.

Sample:

Directive1:-

app.directive('myDirective1', [function () {
    return {
        restrict    : 'E',
        templateUrl : 'templates/myDirective1.html',
        link        : function (scope, elem, attr) {
            scope.items = 'myPara';
        }
}]);

Directive2:-

app.directive('myDirective2', [function () {
    return {
        restrict    : 'E',
        templateUrl : 'templates/myDirective2.html',
        scope       : {
            items : '='
        }
        link        : function (scope, elem, attr) {
            //here i want 'myPara'
        }
}]);

Html:-

<my-directive1 items="items">
  <my-directive2></my-directive2>
</my-directive1>

In the above example, when i change the value of scope.items in Directive1, it should be reflect on directive2 isolated scope(items). Now i can't get the value in Directive2. Can any one help me. Thanks.

Upvotes: 0

Views: 50

Answers (1)

Jordy van Eijk
Jordy van Eijk

Reputation: 2766

Have a service that you inject in both directives..

app.service('myService',function(){ return {myPara : undefined}})

Now add this service to your both directives and use the myPara like myService.myPara = bla because the service is a singleton you will have the same instance in both your directives.

directive1:

app.directive('myDirective1', ['myService',function (myService) {
return {
    restrict    : 'E',
    templateUrl : 'templates/myDirective1.html',
    link        : function (scope, elem, attr) {
        scope.items = myService.myPara;
    }
}]);

directive2

app.directive('myDirective2', ['myService',function (myService) {
return {
    restrict    : 'E',
    templateUrl : 'templates/myDirective2.html',
    scope       : {
        items : '='
    }
    link        : function (scope, elem, attr) {
        //here i want 'myPara'
        myService.myPara // Here is your myPara
    }
}]);

Upvotes: 2

Related Questions