AngularJS过滤器 - 未定义的对象

时间:2015-08-13 10:49:00

标签: angularjs

我在index.html

中得到了这个表达式
{{place.file.name()}}

它包含类似tfss-24af16c3-df1f-4c35-a1e1-281bd3af7c7a-Flightreservation.pdf的字符串。

我想通过过滤器剪切前42个字符:

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

过滤器是:

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

它有效。但是,控制台打印:

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

我在某处读到inputtruefalse(不知道它是否正确)。但它的作用就像input是字符串一样。

为什么它仍然输出错误?

2 个答案:

答案 0 :(得分:1)

错误表示有时您的输入不是字符串。例如,它可能在您的place对象初始化之前。

出于您的目的,您可以使用内置的limitTo过滤器,因为已经有一些检查。它有第二个参数,您可以在其中设置偏移量:

$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 }}

请参阅完整演示的plunker:http://plnkr.co/edit/o1fIh84OhptZrsYZ0vIV?p=preview

答案 1 :(得分:0)

因为在加载内容之前评估了过滤器。您可以检查输入是否包含任何内容:

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

你将不再获得console error