我正在尝试在控制器中准备一个JSON对象。这样我就可以将该对象发送到我的REST服务来插入。事情是我的JSON对象有点棘手,并且有不同的级别。
{
"ilstbusError": [],
"icdoQuestion": {
"idoQuestion": {
"questionId": 1,
"createdBy": 1,
"createdDate": "2015-03-21",
"isValid": 0,
"modifiedBy": 1,
"modifiedDate": "2015-03-21",
"questionHtml": "Is there good explanation of what dark matter could be in space?",
"questionTitle": "What is dark matter?",
"threadId": 1,
"updateSeq": 0
}
}
}
看起来像上面。所以为了填写这个对象,我试着写下面的代码。
$scope.ibusQuestion.icdoQuestion.iQuestion.questionTitle = "questionTitle";
$scope.ibusQuestion.icdoQuestion.iQuestion.questionHtml = "questionHtml";
$scope.ibusQuestion.icdoQuestion.iQuestion.threadId = 1;
$scope.ibusQuestion.icdoQuestion.iQuestion.isValid = 0;
但它给了我以下错误
TypeError: Cannot read property 'icdoQuestion' of undefined
任何人我怎么能做到这一点?
由于 法赫德穆拉吉
答案 0 :(得分:2)
在分配其属性之前,您需要先定义icdoQuestion
基础对象:
$scope.ibusQuestion = {icdoQuestion: {iQuestion: {}}};
$scope.ibusQuestion.icdoQuestion.iQuestion.questionTitle = "questionTitle";
// ...
或者如果你想让它更加花哨而不担心提前定义整个嵌套对象结构,你可以使用Angular $parse
服务:
$parse('ibusQuestion.icdoQuestion.iQuestion.questionTitle').assign($scope, "questionTitle");
在这种情况下,您根本不需要定义$scope.ibusQuestion
,因为如果在$scope
找不到它,Angular会为您创建它。