2013-12-23 81 views
0

我在這裏嘗試了很多不同的東西,沒有運氣。基本上我有一串字符串(只是句子)。我需要ng重複這些並輸出它們。沒問題。但我需要能夠找到並替換特定的文字組合(在這種情況下爲「社會保障」),將其封裝在鏈接中,併爲該鏈接添加ngClick指令。用AngularJS中的ngclick指令代替ngrepeat中的靜態文本內容

我非常確定,我需要使用一個指令,這與編譯和鏈接有關。但就我所能得到的這一點而言。非常感激任何的幫助。

回答

0

我想你可以使用這樣的事情:http://jsfiddle.net/DotDotDot/Z9CHL/2/
我不知道這是最好的實現,但至少它的工作原理

的HTML代碼很簡單,我把自定義指令的一個參數,全句

<ul ng-repeat='sentence in list'> 
     <li><span the-dir txt="sentence"></span></li> 
    </ul> 

在JavaScript端,這是相當容易的,但不再:

.directive('theDir', function($compile){ 
var r=/(social security)/ig; 
return { 
    scope:{txt:'='}, 
    link:function(scope,element,attributes){ 
     scope.aFunction=function(){ 
     console.log('In the directive, you clicked on social security'); 
     } 
     if(r.test(scope.txt)) { 
      splitted=scope.txt.split(r); 
      console.log(splitted) 
      var newSpan=new angular.element('<span>'); 
      for(var i=0;i<splitted.length;i++) 
      { 
       if(r.test(splitted[i])){ 
        var newLink=new angular.element('<a>'); 
        newLink.attr('ng-click','aFunction()'); 
        newLink.addClass('social-security'); 
        newLink.html(splitted[i]); 
        newSpan.append(newLink); 
       } 
       else 
        newSpan.append(splitted[i]); 
      } 
      element.append(newSpan); 
      $compile(newSpan)(scope); 
     } 
     else 
     { 
     element.html(scope.txt); 
     } 

    } 

} 
}); 

我使用正則表達式來查找句子'social security'的所有出現,在這些出現處分割完整句子,然後用新的angular.element替換每個單詞(本例中爲HTML鏈接,用ng-點擊屬性)。我將所有常規單詞和鏈接添加到原始元素,然後$使用工作鏈接編譯新創建的span,以便進行ng單擊。
它似乎工作
我讓你在代碼中挖,我希望它可以幫助你

玩得開心