Angular 过滤器有效,但将输入视为未定义并抛出错误

Angular filter works, but sees input as undefined and throws error

我写了一个看起来工作正常的过滤器,尽管我收到以下错误。

TypeError: Cannot read property 'replaceAll' of undefined

过滤器将错误的相对 URL 替换为绝对 URL。这是过滤器和标记。

//located elsewhere
String.prototype.replaceAll = function(s,r){
    return this.split(s).join(r);
}
//located elsewhere
var imgBase = '<img src="http://discourse.mysite.com';

app.filter('prependImg_topic', function(){
  return function(cooked) {
    return cooked.replaceAll('<img src="//discourse.mysite.com', imgBase);
  }
})

标记:

<div class="topic-post-body" ng-bind-html="topic.post_stream.posts[0].cooked | prependImg_topic "></div> "

我倾向于使用$sce,因为我在ng-bind-html中输入数据。如果我像这样打印值: {{topic.post_stream.posts[0].cooked}} ,它存在,所以我知道它不是未定义的。此外,过滤器可以正常工作并正确写入 url。去搞清楚。

我可以提供帮助回答所需的任何其他详细信息。谢谢。

编辑:另一个可能有帮助的奇怪之处是在 ng-repeat 这个过滤器的内部工作,并且不会抛出任何错误。迷幻的东西!

<div class="post" ng-repeat="post in posts" ng-if="$index > 0">
     <div class="topic-post-body" ng-bind-html="post.cooked | prependImg_topic"></div>
</div>

我想数据是异步加载的,如果是这种情况,难怪过滤器会抛出错误,因为它试图对(尚)不存在的数据进行操作。您所做的检查 {{ topic ... }} 并不能证明任何事情,因为如果数据最终会出现,它将打印数据(最好使用 console.log 检查)。 ng-repeat 中的过滤器不抛出任何错误的原因是因为 ng-repeat 只有在有任何数据要迭代时才会工作,这意味着当 ng-repeat 中的过滤器运行时数据已经存在。 这也是为什么您应该始终以这样一种方式构建过滤器的原因,即它们可以处理 undefinednull 值而不抛出。