如何一起使用继承范围和隔离范围

时间:2015-12-01 07:59:21

标签: javascript angularjs

我有需要排序的html表。

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

所以我创建了自己的名为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();
      };
    }
  }
});

指令有效,当用户点击Name列标题时,名为sort_by的函数知道需要对哪一列进行排序。
问题是它无法调用父控制器在控制器中写入的功能
所以我使用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();
      };
    }
  }
});

最后我可以调用父范围,但问题是我无法将sort_by函数作为参数赋值。

Plunker

1 个答案:

答案 0 :(得分:2)

您可以稍微修正一下link function

此功能有一些参数:scopeelementattributes等。

所以,你可以看到所需属性的值

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

当然这是静态属性值的工作,在这种情况下不需要引号 Updated Plunkr

UPDATE:与第一个功能一样:可以从父作用域调用函数,也可以像

一样传递它
<th custom-sort-one order="'Name'" func="TestFunction()" >Name</th> 

并在指令中使用&

  

&amp; &amp; attr - 提供了在父作用域上下文中执行表达式的方法。