自定义过滤器提供“无法读取未定义的属性‘切片’"在 AngularJS 中 [英] Custom filter giving "Cannot read property 'slice' of undefined" in AngularJS

查看:22
本文介绍了自定义过滤器提供“无法读取未定义的属性‘切片’"在 AngularJS 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的自定义 startFrom 过滤器给我一个错误.

My custom startFrom filter is giving me an error.

app.filter('startFrom', function() {
    return function(input, start) {
        start = +start; //parse to int
        return input.slice(start);
    }
});

app.controller("PostCtrl", function($scope, $http) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.hidePagination = true;

$scope.search = function() {
    $http.get('someurl').then(sucesscalback,errorcalback);
    function sucesscalback(response)
    {
        $scope.hidePagination = false;
        console.log("Success:");
        console.log(response.data.records);
        $scope.posts = response.data;
        $scope.numberOfPages=Math.ceil($scope.posts.records.length/$scope.pageSize); 
        alert($scope.numberOfPages);
    }
    function errorcalback(failure)
    {
        console.log("Error:");
        console.log(failure);
    }

推荐答案

你的过滤器需要检查输入是否存在:

Your filter needs to check whether or not the input exists:

app.filter('startFrom', function() {
    return function(input, start) {
        if (!input || !input.length) { return; }
        start = +start; //parse to int
        return input.slice(start);
    }
});

否则,过滤器函数将运行并因此在 undefined 上调用 slice ,它没有 slice 的属性,如数组或字符串可以.

Otherwise, the filter function will run and thus call slice on undefined which doesn't have a property of slice like an array or string does.

过滤器在没有值时被调用的原因是过滤器会在 Angular 运行它的第一个 $digest 循环时运行.您可以通过在控制器中添加初始值来避免该错误,但最好仅将 if 语句添加到过滤器中.

The reason the filter is called while there is no value is because the filter will run when Angular runs its first $digest cycle. You could avoid the error by adding an initial value in the controller, but it's best just to add the if statement to the filter.

这是两种解决方案的演示.注意没有错误.

这篇关于自定义过滤器提供“无法读取未定义的属性‘切片’"在 AngularJS 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆