我有一些 Angular 代码,我已经开始工作了,但我不明白为什么 - 来自 C Sharp 背景,并且是 JS 和 Typescript 的新手。
<tr ng-repeat="colleague in Model.FilteredColleagueListModel | filter:Model.searchText(Model.SearchCriteria)" >
public searchText(searchCriteria)
{
return function (item) {
if (item.DisplayName.indexOf(searchCriteria) > -1
{
return true;
}
return false;
}
};
我有一个过滤器,但我不明白的是嵌套函数。为什么 item 只能在 return 函数中使用。返回函数也是 TypeScript 中执行此操作的正确方法吗?可以问这样稍微开放式的问题吗?
最佳答案
您使用的模式是有状态过滤器(不鼓励 https://docs.angularjs.org/api/ng/filter/filter )
It is strongly discouraged to write filters that are stateful, because the execution of those can't be optimized by Angular, which often leads to performance issues. Many stateful filters can be converted into stateless filters just by exposing the hidden state as a model and turning it into an argument for the filter.
您应该考虑将 searchCriteria
作为返回函数的参数。那么语法将类似于 filter:Model.searchText:Model.SearchCriteria
public searchText()
{
return function (item, searchCriteria) {
if (item.DisplayName.indexOf(searchCriteria) > -1
{
return true;
}
return false;
}
};
关于javascript - 为什么 Angular 重复过滤器只能访问返回函数中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34130903/