Angular JS TypeError:无法读取路由上未定义的属性“id”
Angular JS TypeError: Cannot read property 'id' of undefined on Route
我正在学习一些AngularJS,我遇到了一个绊脚石。我可以检索我的 jSON 并将其输入前端,但是当我要转到新视图时,我的问题就来了。我的 ID 无法正确输入。基本上,如果单击我的项目 ID 为 1,则其显示 id 为 14。或者我收到类型错误:无法读取未定义的属性"14"
任何想法都会很有帮助。
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];
});
}
假设getAsync
回调中的数据属性是您发布的 JSON 的表示形式,我认为这是因为您尝试通过对象在数组中的位置而不是其 id 属性来访问对象。如果您使用的是下划线/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;
}
}
相关文章:
- 将对象作为参数传递后的未定义属性
- 检查链接对象形式中未定义属性的最佳实践是什么
- PhantomJS中的evalute内部未定义属性
- 访问数字类型的未定义属性
- 如何处理未定义属性的未定义属性 javascript 类型错误
- 返回未定义属性的脚本
- 类型错误:无法读取 ng-repeat 的未定义属性
- JavaScript-Disqus如何处理其“;disqus_config”;包含未定义属性的函数
- 是对HTMLElement#样式的未定义属性的赋值的返回值,保证与赋值相同
- 最好检查未定义属性或设置为空
- 如何解决这个未定义属性的node.js错误?
- 如何在JavaScript中挽救对象的未定义属性?
- AngularJS和PHP -注意:未定义属性:stdClass
- 主干模型删除未定义属性
- if else子句中未定义对象的未定义属性
- Javascript数组问题:无法读取未定义属性
- 当尝试使用未定义属性进行筛选时,Lodash将排除项
- 在Javascript数组的中途未定义属性
- Knockout arrayForEach未定义属性
- javascript中未定义属性的简写,初始化和赋值属性