简体   繁体   中英

AngularJS undefined when using variable

This is my first test application I have been working on using AngularJS and I seem to hitting a few errors on simple things.

I have my AngularJS service which returns JSON to my Controller ( 'crucify' has been specified but this is whatever the user enters in the texbox ):

{"crucify":{"id":37635889,"name":"Crucify","profileIconId":984,"summonerLevel":30,"revisionDate":1450980592000}}

Now in my Controller I want to be able to access the JSON values ' id ' and ' name ' etc. So I have wrote this:

xile.controller('searchController', ['personSearch', '$scope', function (personSearch, $scope) {

$scope.search = function () {

    var summoner = $scope.summoner;

    personSearch.findPlayer(summoner).then(function (data) {
        $scope.answer = data;
    });
}

}]);

So data is equal to the JSON posted above. How in my HTML do I bind the ' id ' and ' name ' from the JSON? I have posted my HTML below but this does not seem to work?

<div>Answer: {{answer.id}}</div>
<div>Answer: {{answer.name}}</div>

EDIT:

The user will enter there username in a textbox:

<input type="text" id="txt_searchUser" ng-model="summoner" />

So Crucify is an example and equals to whatever is entered in this box.

 var key=Object.keys(data) //return ["crucify"], object key $scope.summoner =data[key[0]]; //return object value 

 xile.controller('searchController', ['personSearch', '$scope', function (personSearch, $scope) { $scope.search = function () { var summoner = $scope.summoner; personSearch.findPlayer(summoner).then(function (data) { //first method $scope.answer = data.crucify; //second method $scope.answer = data }); } }]); 
 //first method <div>Answer: {{answer.id}}</div> <div>Answer: {{answer.name}}</div> //second method <div>Answer: {{answer.crucify.id}}</div> <div>Answer: {{answer.crucify.name}}</div> 

Have you tried adding ng-if to your divs, like this?

<div data-ng-if="answer.id">Answer: {{answer.id}}</div>
<div data-ng-if="answer.name">Answer: {{answer.name}}</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM