2016-08-09 36 views
1

我試圖從使用click事件的json響應中獲得標題,當我單擊按鈕時,我設法獲取所有標題,但是如何獲取特定標題取決於用戶點擊了buttona hrefangular2獲取json格式的字符串,然後點擊

modalGetTitle(title) { 
    this.http.get('../../xmlConf/dashboard_journey.json') 
    .map((res:Response) => res.json()) 
    .subscribe(data => { 
     if(data) { 
      var jsonObj = JSON.parse(JSON.stringify(data)); 
      this.oJourney = jsonObj.o.journey; 
      this.getJourneyTitle = this.oJourney; 

      for (var i = 0; i < this.getJourneyTitle.length; i++) { 
       var element = this.getJourneyTitle[i]; 
       console.log(element.title); 
      }  
     } 

    }); 
}; 

像 如果我點擊<button (click)="modalGetTitle()">Title 1</button>,我想呈現JSON響應標題在<span>,因此該按鈕只是觸發功能。

大氣壓我只是從響應得到最後一個項目:

<a href="javascript:;" (click)="modalGetTitle()" class="float-shadow" *ngIf="journey.journey_url == 'javascript:;' ">{{journey.title}} </a> 

回答

1

你可以試試這個,如果我明白你的問題。

<button ng-click="modalGetTitle()"><span id="spanId">Title</span></button> 

在控制器,你可以定義功能

  $scope.modalGetTitle = function(){ 
var title = document.getElementById('spanId').innerHTML 
      this.http.get('../../xmlConf/dashboard_journey.json') 
       .map((res:Response) => res.json()) 
       .subscribe(data => { 
        if(data) { 
         var jsonObj = JSON.parse(JSON.stringify(data)); 
         this.oJourney = jsonObj.o.journey; 
         this.getJourneyTitle = this.oJourney; 

         for (var i = 0; i < this.getJourneyTitle.length; i++) { 

          var element = this.getJourneyTitle[i]; 
     if(element == title){ 
          console.log(element.title); 
     } 
         }  
        } 
       }); 
      } 
+0

但這隻會讓我無論在硬編碼的範圍內?我打算在中顯示標題。按鈕只是爲了觸發該功能。 – nCore

+0

在這種情況下,你可以在這樣的函數集中標題 var title = document.getElementById('spanId')。innerHTML; –

+0

如果語句沒有返回任何內容,我認爲我不需要執行文檔獲取,因爲我可能只是在視圖中{{title}}。看到我對Thierry的回覆。 – nCore

0

你可以通過一些作爲方法的參數。例如:

<button (click)="modalGetTitle('title1')">Title 1</button> 
+0

對不起你能解釋這一點嗎?按鈕只是爲了觸發該功能,我想顯示json響應標題 nCore

+0

對不起,但我不知道你想要做什麼。您將從響應有效載荷中選擇要顯示的標題? –

+0

對不起,我聽起來很迷惑,我收集了一些鏈接(例如JS)和(點擊)事件來觸發該功能,並以(JS)的標題得到響應,並在標記中顯示響應。 – nCore

0

做這樣的

<button (click)="modalGetTitle(this)">Title 1</button> 
function modalGetTitle() { 
    alert(objButton.textContent); // this will show "Title 1" 
}