2016-11-18 5 views
0

I'm new to angular and I'm struggling to replace relative href paths inside my text.角度:交換するフィルタと完全相対<a href="/"> paths

For example purposes, I have the following controller/scope/html/filter:

$scope.text = 'Here you can find the best <a href="/shoes/sport">sport shoes</a>, <a href="/shoes/classic">classic shoes</a> and <a href="/socks/sale">socks</a>. If not, you can <a href="http://www.google.com">google</a> it.'; 

<p ng-bind-html="text | parseUrlFilter"></p> 

I tried to create a filter that search for all relative urls and replace with the complete path url (eg: http://www.example.com/shoes/sporthttp://www.example.com/shoes/classichttp://www.example.com/socks/sale):

app.filter('parseUrlFilter', function() { 

    var urlPattern1 = 'href="/shoes/'; 
    var urlPattern2 = 'href="/socks/'; 

    return function(text) { 


      angular.forEach(text.match(urlPattern1), function(url) { 
       url = url.replace('href="',''); 
       text = text.replace(url, 'http://www.example.com' + url); 
      }); 

      angular.forEach(text.match(urlPattern2), function(url) { 
       url = url.replace('href="',''); 
       text = text.replace(url, 'http://www.example.com' + url); 
      }); 

     return text; 
    }; 

}) 

しかし、私のフィルタは、各パターンのための唯一の最初のケース(http://www.example.com/shoes/sport)を置き換えます。

どのように私はそれが正常に動作し、すべてのマッチやパターンを置き換えることができるか知っているか、または私が必要なものを得るために他の賢い/スマートな方法はありますか?

PS:この角度のあるプロジェクトはIonicプラットフォーム(モバイルアプリ)で、通常はこれらの相対パスを挿入するデスクトップバージョン(php)と共有されているデータベースからデータ(テキスト+リンク)を取得しています。したがって、私はそれらを完了する必要があります。さもなければ、多くのリンクが私のモバイルアプリで壊れてしまいます。

ありがとうございました!

+0

これを最初から実装する必要はありません!あなたは角のルートを確認する必要があります。 https://docs.angularjs.org/api/ngRoute –

+0

こんにちは@EiriniGraonidou問題は、この角度のあるプロジェクトはIonicプラットフォーム(モバイルアプリ)であり、私は共有されているデータベースからデータ(テキスト+リンク)を取得していますこれらの相対パスを挿入するデスクトップバージョン(php)。だから、私はそれらを埋める必要があります。そうしないと、すべてのリンクが私のアプリで壊れてしまいます。 – czmarc

答えて

1

正規表現を試すことができます。次のようなものがあります。

var str = 'Here you can find the best <a href="/shoes/sport">sport shoes</a>, <a href="/shoes/classic">classic shoes</a> and <a href="/socks/sale">socks</a>. If not, you can <a href="http://www.google.com">google</a> it.'; 
var res = str.replace(/href=\"\//g, "href=\"http://www.example.com/"); 

正規表現の 'g'はグローバル置換文字です。

+0

ありがとう!私の場合はうまくいった! – czmarc

関連する問題