我一直在尝试添加自定义过滤器以根据区域设置过滤出主列表。为了获取主列表,我进行了 ajax 调用。在尝试调试时,app.filter
似乎在 ajax 提供响应之前执行。以下是我收到的错误:
angular.js:15712TypeError: Cannot read property 'length' of undefined at messageSelectionCtrl.js:57 at fn (eval at (angular.js:14059), :4:360) at Object. (angular.js:16730) at r.$digest (angular.js:18747) at r.$apply (angular.js:19054) at g (angular.js:13192) at T (angular.js:14196) at XMLHttpRequest.w.onload (angular.js:14364)
以下是我一直在尝试的代码:
messageSelectionCtrl.js:
//getMessageSelectionConfigs is the service used to make http request and the successhandler and errorhandler defined in controller.
app.controller('messageSelectionCtrl',['$scope','getMessageSelectionConfigs', 'filterData', '$log','errorService', function($scope, getMessageSelectionConfigs, filterData, $log, errorService){
$scope.filterData = filterData;
....
...
//service call to fetch message selection config
getMessageSelectionConfigs.get(data).then(messageSelectionSuccessHandler,messageSelectionErrorHandler);
......
}]);
.......
.....
app.filter('filterByLocale', function(){
return function (messageSelectionList, locale){
var filtered = [];
for (var i=0; i<messageSelectionList.length; i++){
var item= messageSelectionList[i];
if(item.locale === locale){
filtered.push(item);
}
}
return filtered;
};
});
.....
..
messageSelectionTemplate.html
<div ng-repeat = "item in messageSelectionList | filterByLocale: filterData.locale">
mainCtrl.js
app.factory('filterData', function(){
return {
locale : ''
};
});
messageSelectionSuccessHandler
函数在错误发生后执行。这很奇怪,因为一旦 ng-repeat 有一些模型要循环,就应该触发 View 。
请让我知道我缺少什么,或者任何指示都会有帮助。
最佳答案
首先初始化 messageSelectionList = [],这样它就永远不会未定义。一旦获取数据,循环就会更新。
并忽略空过滤器 -
app.filter('filterByLocale', function(){
return function (messageSelectionList, locale){
if(locale){
var filtered = [];
for (var i=0; i<messageSelectionList.length; i++){
var item= messageSelectionList[i];
if(item.locale === locale){
filtered.push(item);
}
return filtered;
}
return messageSelectionList
}
};
});
关于javascript - 在模型可用之前调用使用 app.filter 的自定义过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36808534/