单击时,angular2以json格式获取字符串

时间:2016-08-09 13:29:43

标签: javascript jquery json angular

我正在尝试使用click事件从json响应中获取标题,我在单击按钮时设法获取所有标题,但是如何根据{{1获取特定标题用户点击了哪个或button

a href

像 如果我点击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响应标题,那么按钮就是触发该功能。

Atm我只收到回复中的最后一项:

<span>

3 个答案:

答案 0 :(得分: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);
        }
                        }      
                    }
                });
            }

答案 1 :(得分:0)

您可以将某些内容作为方法的参数传递。例如:

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

答案 2 :(得分:0)

这样做

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