刚接触 Angular,并且坚持做一些本应该很简单的事情......
我有一些资源:
.factory( 'RSVPRes', function ( $resource ) {
return {
RSVP: $resource("../reservations/:id.json", {id:'@id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
Meals: $resource('../meals.json'),
UserInvites: $resource('../userinvite.json')
};
})
Meals.json:
[{"id":1,"name":"Chicken","description":"Chicken Yum!","created_at":"2013-12-11T22:37:28.994Z","updated_at":"2013-12-11T22:37:28.994Z","event_id":1,"event":{"name":"Wedding"}},{"id":2,"name":"Steak","description":"9oz","created_at":"2013-12-11T22:37:29.004Z","updated_at":"2013-12-11T22:37:29.004Z","event_id":2,"event":{"name":"Rehersal"}},{"id":3,"name":"Veggie","description":"Vegan","created_at":"2013-12-11T22:37:29.008Z","updated_at":"2013-12-11T22:37:29.008Z","event_id":3,"event":{"name":"Stag"}}]
UserInvites.json:
[{"id":18,"created_at":"2013-12-11T23:00:18.684Z","updated_at":"2013-12-11T23:00:18.684Z","event_id":1,"registry_id":1,"user_id":9,"total_in_party":2}]
数据的格式似乎相同。这里一切都很好。
已编辑现在在我的 Controller 中
.controller('RSVPCtrl', function RSVPController($scope, RSVPRes, $state, $stateParams) {
//GET INVITATION(S)
RSVPRes.UserInvites.query().$promise.then(function(response){
$scope.invitation = response.data;
//BUILD SELECT LIST FOR MEALS
$scope.meals = RSVPRes.Meals.query();
//EDIT
if ($scope.rsvpId) {
$scope.rsvp = RSVPRes.RSVP.get({id: $scope.rsvpId}, function() {
// $scope.selectedUser = $scope.invite.user_id;
// $scope.selectedEvent = $scope.invite.event_id;
// $scope.selectedRegistry = $scope.invite.registry_id;
// $scope.selectedTotalInParty = $scope.invite.total_in_party;
});
}
//NEW
else {
//INITIALIZE EMPTY GUESTS
$scope.guests = [];
for (var i = 0; i < $scope.invitation.total_in_party; i++) {
$scope.guests[i] = {
first_name: '',
last_name: '',
meal: 1,
rsvp: 0
};
}
}
});
$scope.submit = function() {
for (var i = 0; i < $scope.guests.length; i++){
$scope.rsvp = new RSVPRes.RSVP();
$scope.rsvp.first_name = $scope.guests[i].first_name;
$scope.rsvp.last_name = $scope.guests[i].last_name;
$scope.rsvp.meal_id = $scope.guests[i].meal;
$scope.rsvp.rsvp = $scope.guests[i].rsvp;
$scope.rsvp.$save();
}
$state.transitionTo('rsvps');
};
})
检查我的response.data我得到了我的信息,但是我的$scope.invitation仍然未定义...
非常感谢任何帮助!
最佳答案
看起来您的 response.data 将是一个数组,这意味着 [$scope.invitation] 更好地命名为 [$scope.invitations],因为您设置为获取(可能) 超过一个。多次邀请的可能性表明您设置的用于构建空 guest 对象的 For 循环不太正确。也许试试这个...
for (var i = 0; i < $scope.invitation.length; i++){
$scope.guests[i] = [];
for (var j=0; j < $scope.guests[i].total_in_party; j++) {
$scope.guests[i].total_in_party[j] = {
first_name: '',
last_name: '',
meal: 1,
rsvp: 0
};
}
}
}
关于javascript - AngularJS - 使用结果从 Factory 读取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577447/