在 AngularJS 中使用过滤器时出现类型错误

Typerror when using filter in AngularJS

我将此过滤器添加到我的 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 循环中声明吗?

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

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

Checking if your teamDetails.name object is defined or not is good idea, because filter runs on every digest cycle.

过滤器

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

希望对您有所帮助,谢谢。

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

尝试在初始化控制器时将 teamDetails 设置为空,并使用 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