Maurice Wipf
Maurice Wipf

Reputation: 707

AngularJS filters - undefined object

I got this expression in my index.html:

{{place.file.name()}}

it contains a String like tfss-24af16c3-df1f-4c35-a1e1-281bd3af7c7a-Flightreservation.pdf.

I want to cut the first 42 characters by a filter:

{{place.file.name() | sliceFileName}}

The filter is this:

.filter('sliceFileName', function() {
  return function(input) {
    return input.slice(42);
  }
})

And it works. However, the console prints:

[Error] Error: undefined is not an object (evaluating 'input.slice')

I read somewhere that input is either trueor false (don't know if it is correct). But it works as if input is the string.

Why does it still output an error?

Upvotes: 2

Views: 398

Answers (2)

just-boris
just-boris

Reputation: 9746

Error means that sometimes your input is not a string. It could be, for example, before your place object has been initialized.

For your purpose you just can use built-in limitTo filter, because there already is some checks. It has second argument where you can set offset:

$scope.Infinity = Number.POSITIVE_INFINITY // you need to provide that into scope, because you need to set upper bound of limit

{{ string | limitTo:Infinity:42 }}

See plunker with full demo: http://plnkr.co/edit/o1fIh84OhptZrsYZ0vIV?p=preview

Upvotes: 1

Razvan B.
Razvan B.

Reputation: 6771

Because the filter get's evaluated before the content is loaded. You can check if the input has any content:

.filter('sliceFileName', function() {
  return function(input) {
    if(input) return input.slice(42);
  }
})

And you won't get the console error anymore.

Upvotes: 0

Related Questions