Custom filter giving “Cannot read property 'slice' of undefined” in AngularJS

冷暖自知 提交于 2019-12-18 19:07:40

问题


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

回答1:


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

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.

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.

Here's a demo of both solutions. Notice there are no errors.



来源:https://stackoverflow.com/questions/25723455/custom-filter-giving-cannot-read-property-slice-of-undefined-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!