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

后端 未结 1 408
-上瘾入骨i
-上瘾入骨i 2021-01-04 02:34

My custom startFrom filter is giving me an error.

app.filter(\'startFrom\', function() {
    return function(input, start) {
        start = +st         


        
相关标签:
1条回答
  • 2021-01-04 03:32

    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.

    0 讨论(0)
提交回复
热议问题