3

我正在学习一些 AngularJS,但遇到了一个绊脚石。我可以检索我的 JSON 并将其提供给前端,但是当我要去一个新视图时我的问题就来了。我的 ID 没有正确输入。基本上,如果单击具有 id 1 的项目,其显示 id 14。或者我得到 TypeError: Cannot read property '14' of undefined

任何想法都会非常有帮助。

json

[
    {
        "id": 14,
        "title": "new post",
        "excerpt": "EXCERPT",
        "content": "ushajsd"
    },
    {
        "id": 10,
        "title": "last post",
        "excerpt": "test",
        "content": "test"
    },
    {
        "id": 4,
        "title": "middle post",
        "excerpt": "contents to post",
        "content": "contents to post"
    },
    {
        "id": 1,
        "title": "Hello world!",
        "excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
        "content": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!"
    }
]

AngularJS

//Create main module
var module = angular.module('module', [''])

//Services

module.factory('posts', function($http) {
  return {
      getAsync: function(callback) {
          $http.get('/wp-content/themes/ajax/ajax.php').success(callback);
      }
  };
});

// Set up our mappings between URLs, templates, and controllers
function caseStudyConfig($routeProvider) {
  $routeProvider.
    when('/casestudy/:id', {
      controller: caseCtrl,
      templateUrl: '/wp-content/themes/templates/casestudy.php'
    }).
    otherwise({
      redirectTo: '/'
    });
}

// Set up our route so the service can find it
module.config(caseStudyConfig);

//Controllers
function homeCtrl (posts, $scope) {
  posts.getAsync(function(data) {
       $scope.content = data;
  });
}

function caseCtrl (posts, $scope, $routeParams) {
  posts.getAsync(function(data) {
       $scope.content = data[$routeParams.id];
  });
}
4

1 回答 1

1

假设您的getAsync回调中的 data 属性是您发布的 JSON 的表示,我认为这是因为您试图通过它在数组中的位置而不是通过它的 id 属性来访问该对象。如果您使用underscore / lodash,您可以像这样轻松解决这个问题:

function caseCtrl (posts, $scope, $routeParams) {
  posts.getAsync(function(data) {
       // Find the object with id which matches id in route params
       $scope.content = _.findWhere(data, { id: $routeParams.id });
  });
} 

或者您可以编写自己的循环来从集合中检索正确的对象:

function caseCtrl (posts, $scope, $routeParams) {
  posts.getAsync(function(data) {
       $scope.content = getObjectById(data, $routeParams.id);
  });

  function getObjectById(collection, id) {
    for (var i = 0, obj; i < collection.length; i ++) {
        obj = collection[i];
        if (obj.id === id) {
            return obj;
        }
    }
    return null;
  }
}
于 2013-11-06T13:58:41.850 回答