简体   繁体   English

使用变量时未定义AngularJS

[英]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. 这是我一直在使用AngularJS进行的第一个测试应用程序,我似乎在一些简单的事情上遇到了一些错误。

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 ): 我有我的AngularJS服务,该服务将JSON返回到我的控制器( 已指定“ crucify”,但这是用户在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: 现在,在我的控制器中,我希望能够访问JSON值“ id ”和“ name ”等。因此,我这样写:

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. 因此,数据等于上面发布的JSON。 How in my HTML do I bind the ' id ' and ' name ' from the JSON? 如何在HTML中从JSON绑定“ id ”和“ name ”? I have posted my HTML below but this does not seem to work? 我已经在下面发布了我的HTML,但这似乎不起作用?

<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. 因此,Crucify是一个示例,它等于在此框中输入的任何内容。

 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? 您是否尝试过将ng-if添加到div中?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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