nCore
nCore

Reputation: 2097

angular2 get string in json format on click

I'm trying to get the title from json response using a click event, I manage to get all the titles when I click on the button, but how can I get specific title depending on the button or a href the user clicked?

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);
            }      
        }

    });
};

Like if I click on <button (click)="modalGetTitle()">Title 1</button> and I want to render the json response title in a <span>, therefore the button is just to trigger the function.

Atm I'm only getting the last item from the response:

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

Upvotes: 1

Views: 512

Answers (3)

Jasmin Kurtic
Jasmin Kurtic

Reputation: 141

you can try this, if i'm understand your question.

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

in controller you can define function

          $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);
        }
                        }      
                    }
                });
            }

Upvotes: 1

rashfmnb
rashfmnb

Reputation: 10558

do it like this

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

Upvotes: 0

Thierry Templier
Thierry Templier

Reputation: 202286

You could pass something as parameter of your method. For example:

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

Upvotes: 0

Related Questions