1

我正在使用 AngularJs 来获取这个 JSON 对象中的一些信息,特别是作者的名字和姓氏:

{
    "bookid": "1",
    "title": "Spring In Action",
    "publisher": "Manning Publications Co.",
    "isbn": "978-1-935182-35-1",
    "owner": "Catalyst IT Services",
    "publishyear": "2011",
    "image": "C:/imagefolder/spring-in-action.jpg",
    "description": "Totally revised for Spring 3.0, this book is a...",
    "author": [
        {
            "authorid": "1",
            "firstname": "Craig",
            "lastname": "Walls",
            "description": "Craig Walls has been professionally developing software for over 17 years (and longer than that for the pure geekiness of it). He is the author of Modular Java (published by Pragmatic Bookshelf) and Spring in Action and XDoclet in Action (both published by (...)"
        }
    ],
    "media": [
    ],
    "tags": [
        {
            "tagid": "1",
            "tagname": "Java"
        },
        {
            "tagid": "5",
            "tagname": "Spring"
        }
    ],
    "copies": [
        {
            "bookcopyid": "2",
            "location": "Beaverton",
            "status": "available"
        }
    ]
}

我现在拥有的代码是(由 bosco2010 在这个 plunker 中提供的(http://plnkr.co/edit/GbTfJ9)):

var app = angular.module('app', []);

app.factory('JsonSvc', function ($http) {
  return {read: function(jsonURL, scope) {
        return $http.get(jsonURL).success(function (data, status) {
            scope.data = data.author;      

        });
    }};
});

app.controller('MainCtrl', function($scope, JsonSvc) {


    JsonSvc.read('data.json', $scope).then(function () {
    $scope.nestedObj = $scope.data;  

    });


    $scope.name = "world";


});
4

2 回答 2

2

要获取名字和姓氏,您需要引用author[0].firstnameauthor[0].lastname

于 2013-09-30T18:33:04.923 回答
0
var app = angular.module('app', []);

app.factory('JsonSvc', function ($http) {
  return {read: function(jsonURL) {
        return $http.get(jsonURL);
    }};
});

app.controller('MainCtrl', function($scope, JsonSvc) {

  // The return object from $http.get is a promise.  I used .then() 
  // to declare $scope.nestedObj after the http call has finished.
    JsonSvc.read('data.json').then(function (data) {
      console.log(data.data);
    $scope.nestedObj = data.data.level1;  
    });

  // ensure app is working
    $scope.name = "world";

  // Using nested obj within declared scope var doesn't work
  // Uncomment below to break whole app

  // Using nested obj in a function works but throws TypeError
  // Declaring $scope.data.level1.level2 = [] first helps here
  $scope.getLen = function () {
      return $scope.nestedObj ? $scope.nestedObj.level2.length : ''; // return an empty string if the callback didn't happen yet
  };

});

简而言之,同时使用 $htttp 服务返回的 promise 的 success() 函数和 then() 函数是不正确的。此外,将您的范围作为参数传递给您的服务并尝试在那里修改它是错误的。

如果您需要直接在服务和控制器之间进行通信,您可以使用 $rootScope、$broadcat 或两者。我修补了你的代码,现在它可以工作了。

Plunk: http ://plnkr.co/edit/PlJZZn?p=preview

于 2013-09-30T18:35:31.013 回答