2014-10-16 101 views
4

我是AngularJS的新手,但到目前爲止,我已經能夠把所有東西都包裹起來。但OrderBy正在引起我的問​​題。而且我還沒有發現像我這樣的問題。我有一種感覺,那是因爲我錯過了$範圍以及orderBy的實際工作方式。AngularJS OrderBy自定義函數

我正在創建一個列表,該列表將顯示今年NaNoWriMo在我所在地區的作家。我已將用戶分爲工廠,並將其顯示出來。但是,我有問題讓他們排序。名稱和Wordcount排序沒有問題。但是「計算平均字數」根本沒有排序。它甚至不會調用我爲它製作的功能。

這是我的簡化佈局,以及JSFiddle setup (updated)

JS:

(function() { 
var app = angular.module('userList', []); 

app.controller('ListController', ['$scope', 

function ($scope) { 
    $scope.users = userData; 
    $scope.day = 30; 

    $scope.avgWords = function (user) { 
     return Math.floor(user.wordcount/$scope.day); 
    }; 

    $scope.sort = "name"; 
    $scope.sortRev = false; 

    $scope.sortChange = function (field) { 
     if ($scope.sort === field) { 
      $scope.sortRev = !$scope.sortRev; 
      return; 
     } 

     $scope.sort = field; 
     $scope.sortRev = false; 
    }; 

    $scope.sortAvg = function (user) { 
     alert("sorted!"); 
     return Math.floor(user.wordcount/$scope.day); 
    }; 
}]); 

var userData = [{ 
    "name": "Kris", 
     "wordcount": 42382 
}, { 
    "name": "Tim", 
     "wordcount": 60120 
}, { 
    "name": "Elsa", 
     "wordcount": 150675 
}]; 
})(); 

HTML:

<div ng-controller="ListController"> 
<table> 
    <thead> 
     <tr> 
      <th ng-click="sortChange('name');">Username</th> 
      <th ng-click="sortChange('wordcount');">Total Words</th> 
      <th ng-click="sortChange('sortAvg');">Average WPD</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr ng-repeat="user in users | orderBy:sort:sortRev"> 
      <td>{{user.name}}</td> 
      <td>{{user.wordcount}}</td> 
      <td>{{avgWords(user)}}</td> 
     </tr> 
    </tbody> 
</table> 

回答

1

當你點擊的平均WPD標題,您可以設置$ scope.sort到 「avgWords」。因此,orderBy使用此字符串對用戶進行排序,從而通過avgWords字段的值(通常爲undefined)對用戶進行排序。

如果你想使用自定義函數,而不是一個字段進行排序,則必須設置$scope.sort到要排序的功能:

$scope.sort = $scope.avgWords; 

要做到這一點,則在標題NG單擊應是

sortChange(avgWords) 
+0

啊,我錯過了。這應該是這樣設置的。 [這是更新的小提琴](http://jsfiddle.net/btronk/6dma7yhc/1/)。但問題仍然是一樣的。我將點擊設置爲sortChange('sorgAvg')以與該函數相對應,但它從來沒有被調用過。 – 2014-10-16 16:59:06

+0

現在我明白我在做什麼。你是對的。問題在於調用sortChange('avgWords')和sortChange(avgWords)之間的區別。一個尋找屬性,另一個尋找一個功能。這一次,這是由兩個''造成的!謝謝。 – 2014-10-16 17:15:52

+0

爲了確實準確,其他人並沒有專門針對某個功能。無論類型是什麼,它都會查找名爲avgWords的當前作用域的屬性。 – 2014-10-16 19:08:43

2

您可以隨時將平均單詞屬性添加到範圍上的用戶數組中的對象。這樣,每列可通過相應的屬性進行過濾...所以像

http://jsfiddle.net/poppypoop/swer05sx/

$scope.users = userData; 
    $scope.day = 30; 

     for(var i=0; i < $scope.users.length; i++){ 
     $scope.users[i].avgWords = Math.floor($scope.users[i].wordcount/$scope.day); 
    } 
+0

我有同樣的想法,但問題在於用戶可以動態添加。它不會更新新用戶,只會在初始加載時更新用戶。 – 2014-10-16 17:11:44

+0

這樣做更有意義。 avgWords自然應該是「用戶」的屬性。看看這個[小提琴](http://jsfiddle.net/6dma7yhc/2/)。所以在您的Xhr請求之後立即添加它們。 – shxfee 2014-10-16 17:22:59