2013-10-16 126 views
2

我正在嘗試在支持排序的angularjs中創建一個簡單的網格。我無法解決如何爲每個列創建排序指示符,然後將其綁定到控制器上的sortoptions,以便在它們更改時排序指示符也會更改。帶排序指標的表頭

我WIP是在這裏:http://plnkr.co/edit/ZzPYY4ZTD8MvRIMWKEwP?p=preview

我創建表,並在指令包裹它,這樣我可以設置控制器爲onSort的結合和sortoptions

<table> 
    <tr> 
    <thead columnwrap sortoptions="sortoptions" onsort="onSort"> 
     <th><column sortby='id'>Id</column></th> 
     <th><column sortby='name'>Name</column></th> 
    </thead>  
    </tr> 

我的包裝指令非常簡單,沒有做太多:

app.directive('columnwrap', function() { 
    return { 
    restrict: 'A', 
    scope: { 
     sortoptions : '=', 
     onsort: '=' 
    } 

    }; 
}); 

我列指令是所有魔法建議立即進行刪除發生。在那裏,我傾向於在sortoptions,但是因爲這是在父指令中聲明的,所以我不知道該怎麼做,並且因爲這個原因,它在指令中都崩潰了。

app.directive('column', function() { 
    return { 
    restrict: 'E', 
    transclude: true, 
    replace: true, 
    scope: { 
     sortby: '@' 
    }, 
    template: "<span><a ng-click='sort' href='#' ng-transclude></a>" + 
    "<span ng-show='sortby == sortoptions.sortby'>" + // sortoptions does not exist, won't work 
     "<span ng-switch='sortoptions.sortdir'>" + // again, no sortoptions 
     "<span ng-switch-when='asc'> ▲</span>" + 
     "<span ng-switch-when='desc'> ▼</span>" + 
     "</span>" + 
    "</span></span>", 
    link: function(scope, el, attrs) { 

     scope.sort = function() { 
     // Want to check the sortoptions of the controller 
     var sortDir = "desc"; 
     if (sortoptions.sortBy == attrs.sortby) { 
      sortDir = sortoptions.sortBy == "asc" ? "desc" : "asc"; 
     } 
     scope.$parent.onsort(scope.sortby, sortDir) 
     } 
    } 
    }; 
}); 

如何訪問從列指令的sortoptions,並將它使得點擊排序列時,所有列的指標適當地更新?

謝謝!

回答

0

使用orderBy過濾器非常簡單,並採用謂詞(排序)和順序(排序順序)。

文檔已經有一個例子。這個例子是最近我實現它的自我解釋,如果你需要的話,我可以爲你做好準備,如果還有灰色地帶的話。

ng-enjoy

+1

我不認爲這對我有多大用處。排序將在服務器端完成,所以這個幫助程序對我來說並不好。 PLus我的排序指示器是一個asc和desc之間的切換器 –