创建在 ng-repeat 中运行函数的 orderBy 表达式
Creating orderBy expression that runs a function in ng-repeat
我有一群 firstName
和 lastName
的人。我想 ng-repeat
通过它们,然后 orderBy: 'lastName'
。这很好用。
但是,我的 people
数组中的一些 person
只有名字。我希望能够按姓氏排序,并且每当它找到一个名字只有 的人时,就将该名字视为姓氏,即。名字的首字母与其余姓氏按字母顺序排列(希望有意义...)
是否是在我的控制器中编写函数然后在 orderBy:
表达式中调用该变量的情况?我试过了,但没用:
控制器:
self.nameOrder = function(thisOne) {
if (thisOne.lastName == null) {
thisOne.firstName == thisOne.lastName;
}
}
查看:
<p ng-repeat="name in people | orderBy: 'lastName.nameOrder()' ">{{lastName}}</p>
我知道以上可能是完全错误的,但我认为最好至少展示一下我一直在尝试的东西,这样我的意图就更清楚了:/
如有任何帮助,我们将不胜感激。提前致谢。
可能问题出在:
thisOne.firstName == thisOne.lastName;
那一行应该是:
thisOne.firstName = thisOne.lastName;
该函数应该是 getter,即 return orderBy
将用来比较所有用户的值。
您的函数没有 return 任何东西。此外,您没有将函数作为参数传递给 orderBy
。代码应该是:
self.nameOrder = function(thisOne) {
// return lastName, or firstName if lastName is null
return thisOne.lastName || thisOne.firstName;
}
和 html 应该使用
ng-repeat="name in people | orderBy:vm.nameOrder"
(假设 vm
是您的控制器使用的别名)
我有一群 firstName
和 lastName
的人。我想 ng-repeat
通过它们,然后 orderBy: 'lastName'
。这很好用。
但是,我的 people
数组中的一些 person
只有名字。我希望能够按姓氏排序,并且每当它找到一个名字只有 的人时,就将该名字视为姓氏,即。名字的首字母与其余姓氏按字母顺序排列(希望有意义...)
是否是在我的控制器中编写函数然后在 orderBy:
表达式中调用该变量的情况?我试过了,但没用:
控制器:
self.nameOrder = function(thisOne) {
if (thisOne.lastName == null) {
thisOne.firstName == thisOne.lastName;
}
}
查看:
<p ng-repeat="name in people | orderBy: 'lastName.nameOrder()' ">{{lastName}}</p>
我知道以上可能是完全错误的,但我认为最好至少展示一下我一直在尝试的东西,这样我的意图就更清楚了:/
如有任何帮助,我们将不胜感激。提前致谢。
可能问题出在:
thisOne.firstName == thisOne.lastName;
那一行应该是:
thisOne.firstName = thisOne.lastName;
该函数应该是 getter,即 return orderBy
将用来比较所有用户的值。
您的函数没有 return 任何东西。此外,您没有将函数作为参数传递给 orderBy
。代码应该是:
self.nameOrder = function(thisOne) {
// return lastName, or firstName if lastName is null
return thisOne.lastName || thisOne.firstName;
}
和 html 应该使用
ng-repeat="name in people | orderBy:vm.nameOrder"
(假设 vm
是您的控制器使用的别名)