admin管理员组

文章数量:1335179

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.

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.

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.

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

<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".

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 controller that IS working:

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}}.

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?

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):

[
    {
        "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"
        ]
    }
]

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.

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.

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.

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

<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".

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 controller that IS working:

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}}.

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?

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):

[
    {
        "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"
        ]
    }
]
Share Improve this question edited Mar 7, 2014 at 20:33 Isaiah Lee asked Mar 7, 2014 at 20:26 Isaiah LeeIsaiah Lee 6873 gold badges10 silver badges19 bronze badges 4
  • I only say this because bags is plural, so I just want to make sure. What is returned in the JSON? Is it a list? A hash? Also, are you sure the content-type header is being returned properly? Your angular code might be parsing the response as a string, which won't have an id property – Ian Commented Mar 7, 2014 at 20:29
  • Hey Ian, I just updated my post with the full paste of the .json file. It's small, and I think it's a list of key-value pairs? How can I check for the content-type header or modify it? It's strange because I didn't have to use any of that with my other controllers.. – Isaiah Lee Commented Mar 7, 2014 at 20:34
  • 2 if it is in an array you have to say bags[1].id – Nick Commented Mar 7, 2014 at 20:36
  • Thanks, Nick. That seemed to solve the problem. I guess since this .json file only has one item in focus, I didn't need to make it into an array. I feel really silly, but thanks a bunch! – Isaiah Lee Commented Mar 7, 2014 at 20:41
Add a ment  | 

3 Answers 3

Reset to default 3

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

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

Just in case someone es 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.

[
    {
        "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.

When he tried to use the expression {{bags.id}} it didn't work because bags was 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.

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.

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

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.

Thanks for the help everyone!

本文标签: javascriptAngularJSCan39t access retrieved JSON data in the viewStack Overflow