javascript - 在模型可用之前调用使用 app.filter 的自定义过滤器

标签 javascript angularjs http

我一直在尝试添加自定义过滤器以根据区域设置过滤出主列表。为了获取主列表,我进行了 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/

相关文章:

javascript - AngularJs 上传按钮功能

java - HttpSession.invalidate() 和 TCPDUMP

javascript - 返回下载文件的发布请求

javascript - 尝试使用 ajax 加载 getorgchart 时出错

javascript - 当从下拉列表中选择项目时以及在将所选项目插入 ng-model 之前,如何进行一些逻辑?

javascript - 在隔离作用域指令中,在作用域上定义变量和在 Controller 上定义变量之间有什么区别吗?

c - 如何让C程序发出HTTP请求并读取响应?

javascript - 忽略 JavaScript 获取响应中的正文

java - 在 Java 中获取 Nashorn JsonObject

javascript - 在 Vue JS 中编辑数组中的项目描述