【问题标题】:Typerror when using filter in AngularJS在 AngularJS 中使用过滤器时出现类型错误
【发布时间】:2015-02-25 20:46:45
【问题描述】:

我将此过滤器添加到我的 Angular 应用程序中以从加载的数据中删除某些字符串:

.filter('cleanteam', function () {
    return function (input) {
        return input.replace('AFC', '').replace('FC', '');
    }
});

 <h2 class="secondary-title">{{teamDetails.name |  cleanteam }}</h2>

你可以在这里看到错误:

http://alexanderlloyd.info/epl/#/teams/61

我的控制器看起来有点像这样:

  .controller('teamController', function($scope, $routeParams, footballdataAPIservice) {
    $scope.id = $routeParams.id;
    $scope.team = [];
    $scope.teamDetails = [];
    //$scope.pageClass = '';



  $scope.$on('$viewContentLoaded', function(){
      $scope.loadedClass = 'page-team';
  });



    footballdataAPIservice.getTeam($scope.id).success(function (response) {
        $scope.team = response; 
    });

    footballdataAPIservice.getTeamDetails($scope.id).success(function (response) {
        $scope.teamDetails = response; 
    });

  })

为什么会发生这种情况?是不是因为 teamDetails.name 没有在 ng-repeat 循环中声明?

【问题讨论】:

  • 您的过滤器应该在更换内部过滤器之前处理未定义的条件

标签: javascript angularjs angularjs-filter


【解决方案1】:

通过查看您的代码,您似乎没有处理未定义的情况,而您的 teamDetails.name 可以是未定义的 undefined,直到它从服务中获取数据。

因为当您尝试通过 ajax 获取数据表单服务时,您的输入变量未定义,当过滤器代码尝试对未定义对象应用 .replace 方法时,它将永远无法工作(.replace() 仅适用于字符串)

检查您的teamDetails.name 对象是否已定义是好的 想法,因为过滤器在每个 digest 循环上运行。

过滤器

.filter('cleanteam', function () {
    return function (input) {
      return angular.isDefined(input) && input != null ? //better error handling
             input.replace('AFC', '').replace('FC', ''):'';
    }
});

希望对你有帮助,谢谢。

【讨论】:

  • 是的,@pankajparkar 可能会在还没有数据的情况下渲染模板,根据我的经验,您几乎总是必须处理它。对于更具可读性的代码,您也可以使用 typeof(input) === 'undefined' 条件。
  • 感谢@bevada 的建议,angular.isDefined(input) 会更有角度,
  • @bevada 我们需要检查input != null吗?似乎 replace() on null 永远不会起作用
【解决方案2】:

在我看来,过滤器正在尝试在您的异步调用完成之前执行。

在初始化控制器时尝试将 teamDetails 设置为 null,并使用 ng-if 防止 DOM 元素在数据到达之前加载:

$scope.id = $routeParams.id;
$scope.team = [];
$scope.teamDetails = null;

<h2 class="secondary-title" ng-if="teamDetails">{{teamDetails.name |  cleanteam }}</h2>

这将确保过滤器在异步调用填充teamDetails 对象之前不会执行。

更多关于ng-if:https://docs.angularjs.org/api/ng/directive/ngIf

【讨论】:

    猜你喜欢
    • 2012-11-19
    • 2014-11-11
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多