在模型可用之前调用使用 app.filter 的自定义筛选器

Custom filter using app.filter getting called before model is available

本文关键字:filter 自定义 app 筛选 调用 模型      更新时间:2023-09-26

我一直在尝试添加我的自定义过滤器以根据语言环境过滤掉主列表。为了获得主列表,我正在放置一个 ajax 调用。在尝试调试时,看起来app.filter似乎在 ajax 提供响应之前执行。以下是我收到的错误:

角度.js:15712类型错误:无法读取未定义的属性"长度" at 消息选择Ctrl.js:57 at FN (评估在 (Angular.js:14059), :4:360) 在对象。(角度.js:16730) 在R.$digest(角度.js:18747) 在R.$apply (Angular.js:19054) 在 G (角度.js:13192) 在 T (角度.js:14196) at XMLHttpRequest.w.onload (angular.js:14364)

以下是我一直在尝试的代码

消息选择Ctrl.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;
  };
});
.....
..

消息选择模板.html

<div ng-repeat = "item in messageSelectionList | filterByLocale: filterData.locale">

主按.js

app.factory('filterData', function(){
  return {
    locale : ''
  };
});

messageSelectionSuccessHandler函数在错误出现后执行。这很奇怪,因为一旦ng-repeat有一些模型可以循环,就应该触发视图。请让我知道我错过了什么,或者任何指示都会有所帮助。

首先初始化消息选择列表 = [],使其永远不会未定义。获取后,循环将使用数据进行更新。

并忽略空过滤器 -

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
  }
  };
});