Angular指令:父模具的子模板

时间:2015-05-16 12:55:56

标签: angularjs inheritance directive

我试图找出指令如何在角度中起作用。我想排序一个表,但我有一个child指令的问题。我不知道如何使用父指令中使用的变量。 (代码用coffeescript编写)

查看HTML

<table extend-table table-params="tableParams">
    <thead>
       <tr>
         <th field="number">Number</th>
         <th field="name">Name</th>
       </tr>
</table>

控制器:字段是已排序的字段

$scope.tableParams =
  field: "name"
  sorting: "asc"

父指令:我解析所有th,用field attr选择th并将child指令添加到它

class ExtendTable
  constructor: ($compile) ->

     link = (scope, element, attrs) ->
        angular.forEach element.find('th'), (th) ->
           th = angular.element(th)

           if th.attr("field")
              field = th.attr("field")

              th.append $compile('<sort-column></sort-column>') scope

              th.bind 'click', () ->
                 if scope.tableParams.field != field
                     scope.tableParams.field   = field
                     scope.tableParams.sorting = 'asc'
                 else
                     if scope.tableParams.sorting == 'asc'
                         scope.tableParams.sorting = 'desc'
                     else
                         scope.tableParams.sorting = 'asc'

     return {
       restrict: 'A'
       scope: true
       link
     }
@myApp.directive 'extendTable', ['$compile', ExtendTable]

Child指令:tableParams.field是已排序的列,而字段是单击的列

class SortColumn

  constructor: () ->
    return {
      restrict: 'E'
      scope:true
      require: '^extendTable'
      template: '<div class="pull-right">
                   <i ng-class="{
                         \'fa\':true, 
                         \'fa-sort\':scope.tableParams.field!=field, 
                         \'fa-sort-asc sort-active\':scope.tableParams.field==field&&scope.tableParams.sorting==\'asc\', 
                         \'fa-sort-desc sort-active\':scope.tableParams.field==field&&scope.tableParams.sorting==\'desc\'}"
                   ></i>
                 </div>'
    }
@myApp.directive 'sortColumn', [SortColumn]

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

要么不制作一个孤立的范围(scope:true - &gt; scope:false),那么您可以通过tableParams访问ng-class(您不必使用范围。)。如果scope为false,则其引用父作用域。 如果您离开scope: true,则可以使用$parent.tableParams访问父范围变量。 您在ng-class中使用的field未分配给任何范围。它是迭代中的局部变量,在此处无法访问。您必须将其分配给范围或子范围。