Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }
like image 866
Fahad Khan Avatar asked Sep 08 '14 11:09

Fahad Khan


1 Answers

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.

like image 174
m59 Avatar answered Oct 14 '22 09:10

m59