javascript AngularJS - 无法在视图中访问检索到的 JSON 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22260031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:47:44  来源:igfitidea点击:

AngularJS - Can't access retrieved JSON data in the view

javascriptjsonangularjsangularjs-scope

提问by Isaiah Lee

I just spent the last hour searching and reading a bunch of similar stackoverflow pages and was unable to find a solution. I'll try to be as descriptive as possible, but please let me know if I need to provide any other details.

我刚刚花了最后一个小时搜索和阅读了一堆类似的 stackoverflow 页面,但找不到解决方案。我会尽量做到描述性,但如果我需要提供任何其他详细信息,请告诉我。

Basically, I'm trying to grab a .json file using $http GET. Once I get it, I'll store it in $scope.bags and then on my html (view) page, I am trying to access the contents to use such as title, details, images, etc.

基本上,我正在尝试使用 $http GET 获取 .json 文件。一旦我得到它,我会将它存储在 $scope.bags 中,然后在我的 html(视图)页面上,我尝试访问要使用的内容,例如标题、详细信息、图像等。

Lets start with the controller:

让我们从控制器开始

munyApp.controller('productController', ['$scope', '$location', '$http',
    function ($scope, $location, $http) {
        var $url2parse = $location.path();
        var $urlSplit = $url2parse.split("/");
        var $bag2show = $urlSplit.pop();        
        var $bag2showString = String($bag2show);
        console.log($bag2showString);

        $http({method: 'GET', url: 'handbags/n1-black-details.json'}).success(function(data) {
            $scope.bags = data;
            console.log($scope.bags);
            $scope.message = "it works!";
        });     

For now, please ignore the random var lines. I'll get to that later, as I'm guessing it's not related to my issue here.

现在,请忽略随机 var 行。我稍后再谈,因为我猜这与我的问题无关。

And here's a small block of the HTMLwhere the controller is to be used:

这是要使用控制器的一小段HTML 代码

<div id="detail_large_container" ng-controller="productController">
    {{bags.id}}
    {{bags['id']}}
</div>

For some reason, I cannot get the id value to show up, which is supposed to be "n1-black".

出于某种原因,我无法显示 id 值,它应该是“n1-black”。

This may seem really simple (it probably is, I'm a beginner with all of this), but the reason this is all perplexing to me is that I was able to do this same thing for another controller and it works out fine. I copy and pasted the working controller to modify as this newer one, and for whatever reason it doesn't seem to work.

这看起来真的很简单(可能是,我是所有这些的初学者),但让我感到困惑的原因是我能够为另一个控制器做同样的事情,而且效果很好。我复制并粘贴了工作控制器以修改为这个较新的控制器,无论出于何种原因它似乎都不起作用。

Here's an example of another controllerthat ISworking:

下面是一个例子另一个控制器IS的工作:

munyApp.controller('handbagsController', ['$scope', '$http',
    function ($scope, $http) {
        $http.get('handbags/bagsfull.json').success(function(data) {
            $scope.bags = data;
        });
}]);

With this above controller, it grabs the json file fine and I'm able to use its contents in the html page by using {{bags.somekey}}.

使用上面的控制器,它可以很好地抓取 json 文件,我可以通过使用 {{bags.somekey}} 在 html 页面中使用它的内容。

Some curious things that I ran into:

我遇到的一些奇怪的事情:

  1. On my new controller, it failed to fetch the .json file when I used the $http.get()syntax. It only started to fetch it successfully when I changed the syntax to use the $http({method: 'GET', url: ''})style. Why I had to change it is really confusing to me. I have all my controllers stored in the same .js file and my older ones use the $http.get() fine, while my newer one fails.
  2. I included a $console.log($scope.bags) after setting $scope.bags to the data that was fetched from the .json file. In my chrome console, it shows that it fetched the .json file fine. It correctly returned my .json file with all the data intact. But when I try to use the data in my html, it's just blank.
  3. For testing, I set a $scope.message = "it works" inside the $http.success function. When I use {{$scope.message}} in the html, it displays the message correctly. This leads me to believe I'm using the $scope correctly (my understanding of $scope is still pretty limited). So what is boggling is that the .json is being correctly fetched (as I can see in my console), and the html can display the $scope.message but can't use the $scope.data from the .json.
  4. Lastly, all those random var lines in the controller's code was just a way for me to grab the part of the URL after the last "/". It's using just standard JS code, which I think is okay. Maybe it's not?
  1. 在我的新控制器上,当我使用$http.get()语法时,它无法获取.json文件。当我更改语法以使用$http({method: 'GET', url: ''})样式时,它才开始成功获取它。为什么我必须改变它对我来说真的很困惑。我所有的控制器都存储在同一个 .js 文件中,我的旧控制器使用 $http.get() 很好,而我的新控制器失败了。
  2. 在将 $scope.bags 设置为从 .json 文件中获取的数据后,我包含了一个 $console.log($scope.bags) 。在我的 chrome 控制台中,它显示它很好地获取了 .json 文件。它正确返回了我的 .json 文件,所有数据都完好无损。但是当我尝试在我的 html 中使用数据时,它只是空白。
  3. 为了测试,我在 $http.success 函数中设置了 $scope.message = "it works"。当我在 html 中使用 {{$scope.message}} 时,它会正确显示消息。这让我相信我正确地使用了 $scope(我对 $scope 的理解仍然非常有限)。所以令人难以置信的是 .json 被正确获取(正如我在控制台中看到的那样),并且 html 可以显示 $scope.message 但不能使用 .json 中的 $scope.data。
  4. 最后,控制器代码中的所有这些随机 var 行只是我获取最后一个“/”之后的 URL 部分的一种方式。它只使用标准的 JS 代码,我认为这没问题。也许不是?

Any help or insight regarding this would be greatly appreciated. Please let me know if you need any other information that'd be helpful for this!

对此的任何帮助或见解将不胜感激。如果您需要任何其他对此有帮助的信息,请告诉我!

Here's the .json file contents below (as requested):

这是下面的 .json 文件内容(根据要求):

[
    {
        "id": "n1-black",
        "title": "n&deg;1 (Black)",
        "description": "TOTE IN TEXTURED CALFSKIN\nBLACK\n001",
        "images": [
            "images/handbags/details/n1-black-1.jpg",
            "images/handbags/details/n1-black-2.jpg",
            "images/handbags/details/n1-black-3.jpg",
            "images/handbags/details/n1-black-4.jpg"
        ]
    }
]

回答by G Amini

Just a guess, but you probably need to parse the JSON before you can use it.

只是猜测,但您可能需要先解析 JSON,然后才能使用它。

Try this:

试试这个:

$http({method: 'GET', url: 'handbags/n1-black-details.json'}).success(function(data) {
    $scope.bags = JSON.parse(data);
    console.log($scope.bags);
    $scope.message = "it works!";
}); 

回答by Nick

Just in case someone comes across this with a similar problem I will provide an explanation.

以防万一有人遇到类似问题,我将提供解释。

If you take a look at his JSON file you will see that it contains a JSON array with one item in it.

如果您查看他的 JSON 文件,您将看到它包含一个 JSON 数组,其中包含一项。

[
    {
        "id": "n1-black",
        "title": "n&deg;1 (Black)",
        "description": "TOTE IN TEXTURED CALFSKIN\nBLACK\n001",
        "images": [
            "images/handbags/details/n1-black-1.jpg",
            "images/handbags/details/n1-black-2.jpg",
            "images/handbags/details/n1-black-3.jpg",
            "images/handbags/details/n1-black-4.jpg"
        ]
    }
]

In the success block he assigned the response of a get request for the JSON file to the bags variable on his $scope.

在成功块中,他将对 JSON 文件的 get 请求的响应分配给他的 $scope 上的 bags 变量。

When he tried to use the expression {{bags.id}}it didn't work because bagswas not an object but an array of objects. When he used {{bags[0].id}}it worked because bags[0]was the actual object he was expecting.

当他尝试使用该表达式时,{{bags.id}}它不起作用,因为bags它不是一个对象,而是一个对象数组。当他使用{{bags[0].id}}它时,它起作用了,因为这bags[0]是他所期待的实际对象。

回答by Isaiah Lee

I found the solution, with the help of Nick. It still doesn't make sense to me why it worked this way but it did.

在尼克的帮助下,我找到了解决方案。我仍然不明白为什么它会以这种方式工作,但确实如此。

I had to state which part of the .json object I was using by stating {{bags[0].something}} instead of {{bags.something}}. I'm still a little unsure why, as my json file only has one object in it. I'm guessing I just have to write it like that regardless of the number of objects in it.

我必须通过声明 {{bags[0].something}} 而不是 {{bags.something}} 来说明我使用的是 .json 对象的哪一部分。我仍然有点不确定为什么,因为我的 json 文件中只有一个对象。我猜我只需要这样写就可以了,不管里面有多少对象。

Also, the real reason why I was having trouble was because of where I was putting the ng-controllerin my html page.

另外,我遇​​到问题的真正原因是因为我将ng-controller放在我的 html 页面中。

What I did was put it inside a div called A, and was trying to access data that was fetched using that controller from another div called B. It makes sense to me now why this doesn't work, and I think I just took another step closer into wrapping my head around the whole MVC idea.

我所做的是将它放在一个名为A的 div 中,并试图访问使用该控制器从另一个名为B 的div 中获取的数据。现在对我来说为什么这行不通是有道理的,我想我只是更接近了一步,让我的头脑围绕整个 MVC 想法。

Thanks for the help everyone!

感谢大家的帮助!