我寫了一個過濾器,似乎工作正常,雖然我得到以下錯誤。角度過濾器的作品,但看到輸入爲undefined並拋出錯誤
TypeError: Cannot read property 'replaceAll' of undefined
過濾器替換絕對那些錯誤相對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}}
,它存在,所以我知道它不是未定義的。此外,該過濾器的工作原理和正確寫入網址。去搞清楚。
我可以提供任何其他幫助解答的詳細信息。謝謝。
編輯:另一個可能有幫助的古怪是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>
它們是異步加載的,但是通過服務的承諾加載,如果它可用於視圖,它也可用於過濾器AFAIK。我實際上認爲它是一種競爭條件,內部的'ng-bind-html'指令需要一點時間來解析html,因此過濾器無法訪問它。 ps我沒有downvote你,謝謝你的幫助。 – cpk 2015-03-31 20:35:25
是的,這是真的,它**將可用,這意味着此時'topic.post_stream.posts [0] .cooked'的值是'未定義的',但這並不會阻止過濾器在這個價值上運作。由於該值爲'undefined'** atm **,所以過濾器會拋出錯誤,因爲未定義的錯誤消息中沒有提供方法replaceAll。 – getOffMyLawn 2015-03-31 20:39:40
您使用'{{...}}進行檢查不會拋出的原因是$ interpolate服務知道如何處理'undefined'值。 – getOffMyLawn 2015-03-31 20:41:17