Frank Myat Thu
Frank Myat Thu

Reputation: 4474

how to use inheritance scope and isolated scope together

I have html table which is needed to sort.

<table>
    <thead>
        <tr>
            <th custom-sort-one order="'Name'" >Name</th>               
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Name_AAA</td>               
        </tr>           
    </tbody>
</table>

So I created my own directive named customSortOne.

app.directive("customSortOne", function() {
  return {
    restrict: 'A',
    transclude: true,
    /// Isolated scope
    scope: {
      order: '='
    },
    template: '<a href="#" ng-click="sort_by(order)" style="color: #555555;"><span ng-transclude></span></a>',
    link: function(scope) {
      scope.sort_by = function(ColumnToSort) {
        console.log("ColumnToSort =", ColumnToSort);
        /// Below function cannot be called because it is in isolated scope.
        scope.TestFunction();
      };
    }
  }
});

Directive working, when user click Name column header, function named sort_by know which column is required to sort.
Problem is it cannot call parent scope's function which is written in controller.
So I change my directive using inherited scope.

app.directive("customSortTwo", function() {
  return {
    restrict: 'A',
    transclude: true,
    /// Inheritance scope
    scope: true,
    template: '<a href="#" ng-click="sort_by(order)" style="color: #555555;"><span ng-transclude></span></a>',
    link: function(scope) {
      scope.sort_by = function(ColumnToSort) {
        /// ColumnToSort is undefined which is not what I want
        console.log("ColumnToSort =", ColumnToSort);
        /// Below function can be executed because I changed to Inheritance scope.
        scope.TestFunction();
      };
    }
  }
});

Finally I can call parent scope, but problem is I cannot give value to sort_by function as an argument.

Plunker

Upvotes: 0

Views: 59

Answers (1)

Grundy
Grundy

Reputation: 13381

You can just a bit fix your link function.

This function have a few parameters: scope, element, attributes and etc.

So, you can just see value for needed attribute

link: function (scope,elem, attrs) {
    scope.order = attrs.order; 

Ofcourse this work for static attribute value, and in this case not needed quotes.
Updated Plunkr

UPDATE: as for first function: you can call function from parent scope, just also pass it like

<th custom-sort-one order="'Name'" func="TestFunction()" >Name</th> 

and in directive use &

& or &attr - provides a way to execute an expression in the context of the parent scope.

Upvotes: 2

Related Questions