使用AngularJS的第一个项目,我使用选择列表将默认值设置为新的第一个选项,或者如果编辑选择值,我有点卡住了。
我有一个包含两个选择列表的表单。注意,我在想我的ng-options标签是错的。
invite.tpl.html
<select ng-model="selectedUser" ng-options="user.id as user.user_name for user in users"></select>
<select ng-model="selectedEvent" ng-options="event.id as event.name for event in events"></select>
获取/发布JSON的控制器。
invite.js
.controller('InviteCtrl', function InviteController( $scope, InviteRes, $state, $stateParams ) {
$scope.inviteId = parseInt($stateParams.inviteId, 10);
$scope.users = InviteRes.Users.query();
$scope.events = InviteRes.Events.query();
//EDIT (HAVE ID) - SET SELECTS TO THE USER/EVENT
if ($scope.inviteId) {
$scope.invite = InviteRes.Invites.get({id: $scope.inviteId});
$scope.selectedUser = $scope.invite.user_id;
$scope.selectedEvent = $scope.invite.event_id;
}
//NEW (NO ID) - SET DEFAULT OPTIONS TO FIRST USER/EVENT
else {
$scope.selectedUser = $scope.users[0];
$scope.selectedEvent = $scope.events[0];
$scope.invite = new InviteRes.Invites();
}
保存功能。
$scope.submit = function() {
$scope.invite.user_id = $scope.selectedUser;
$scope.invite.event_id = $scope.selectedEvent;
//IF ID - UPDATE ELSE NEW
if ($scope.inviteId) {
$scope.invite.$update(function(response) {
$state.transitionTo('invites');
}, function(error) {
$scope.error = error.data;
});
}
else {
$scope.invite.$save(function(response) {
$state.transitionTo('invites');
}, function(error) {
$scope.error = error.data;
});
}
};
获得这些资源
.factory( 'InviteRes', function ( $resource ) {
return {
Invites: $resource("../invites/:id.json", {id:'@id'}, {'update': {method:'PUT'}, 'remove': {method: 'DELETE', headers: {'Content-Type': 'application/json'}}}),
Users: $resource('../users.json'),
Events: $resource('../events.json'),
};
})
我环顾四周,发现了一些文章解释了如何做到这一点,但我尝试的所有内容都给了我设置值或保存表单的问题。
答案 0 :(得分:1)
资源API不会立即返回 - 请参阅docs以获取以下声明:
重要的是要意识到调用$ resource对象方法 立即返回空引用
可能只是因为你试图在值可用之前分配它吗?
您可以将代码更改为:
if ($scope.inviteId) {
$scope.invite = InviteRes.Invites.get({id: $scope.inviteId}, function() {
$scope.selectedUser = $scope.invite.user_id;
$scope.selectedEvent = $scope.invite.event_id;
});
}
就select指令而言,我倾向于使用对象而不是值,例如
<select ng-model="selectedUser" ng-options="user.user_name for user in users"></select>
// in controller:
$scope.selectedUser = $scope.users[1];