Question

I have a directive inner which I want to wrap into another directive comp to hide some complexity of inner directive. "Comp" defines the clickAction which should be executed by the "inner" directive.

Now I have some troubles to bind correctly to the "clickAction" of inner directive from comp directive.

If I explicitly apply click-action="clickAction()" it's works, but not desired in that way.

template: '<inner ng-model="data" click-action="clickAction()"></inner>',

I think I have to add some "magic" in the link function to bind to the clickAction

Plunker: http://plnkr.co/edit/AXf1oL?p=preview

1) How can I achieve this (simple) scenario. 2) Is this the right approach to "wrap" the inner directive?

Était-ce utile?

La solution

You should wrap clickAction with another function inside "inner" directive scope.

Comp directive has no changes.

app.directive('comp', [function() {
    return {
        scope: {
            data: '=ngModel'
        },
        restrict: 'AE',
        template: '<inner ng-model="data" click-action="clickAction()"></inner>',
        link: function(scope, ele, attrs) {
               scope.clickAction = function() {
                alert('click');
            };
        }
    };
}]);

inner directive should have function with diferent name from "clickAction" which calls this action:

app.directive('inner', [function() {
    return {
      scope: {
          data: '=ngModel',
          clickAction: '&',
      },
      require: ['ngModel'],
      restrict: 'AE',
      //replace: true, // optional 
      template: '<div ng-click="onClick()">{{data.value}}</div',
      link: function(scope, ele, attrs) {
          scope.onClick = function(){
            alert('inner');
            scope.clickAction();  
          };
        }
  };
}]);

Plunkr: http://plnkr.co/edit/Y9OoK0tGqTWlXNFEZuDr?p=preview

If you want to pass arguments between function you can do it by using:

Template:

template: '<inner ng-model="data" click-action="clickAction(params)"></inner>',

Click action:

scope.clickAction = function(params) {
    alert(params);
};

Click action inside inner directive:

scope.onClick = function(){
    alert('inner');
    scope.clickAction({params: "yo dawg!"});  
};

Ad. your question: I don't see anything wrong in placing directive inside directive.

EDIT

If you dont want to define click-action=clickAction() you shouldn't create isolated scope in inner directive. Then your inner directive will use scope of outer directive and also u will not need to wrap clickAction() with another function.

There is plunkr with this solution: http://plnkr.co/edit/jKg1R4Bn3TvZPOTLtLZn?p=preview

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top