我在将选择元素的选项列表中的项目设置为选定状态时遇到问题。我的服务器后端是 Django 1.5,使用 TastyPie 作为 API。
模板(简化)
<select
ng-model='dataService.major_minor.department'
ng-options='d.name for d in dataService.departments'
name='department'
class='select2'
required>
</select>
数据服务
majorMinor.factory('dataService', function($rootScope, Restangular) {
var self = {};
self.degrees = [];
self.departments = [];
self.major_minor = false;
self.majors_and_minors = [];
self.fetch_degrees = function() {
Restangular.all('degree').getList().then(function(results) {
self.degrees = results;
});
};
self.fetch_departments = function() {
Restangular.all('department').getList().then(function(results) {
self.departments = results;
});
};
self.fetch_major_minor = function(majorMinorID) {
Restangular.one('major-minor', majorMinorID).get().then(function(result) {
self.major_minor = result;
});
};
self.fetch_major_minor_list = function() {
Restangular.all('major-minor').getList().then(function(results) {
self.majors_and_minors = results;
});
};
self.fetch_degrees();
self.fetch_departments();
self.fetch_major_minor_list();
return self;
});
Controller
majorMinor.controller('EditCtrl',
function($scope, $routeParams, dataService) {
$scope.dataService = dataService;
$scope.dataService.major_minor = false;
$scope.dataService.fetch_major_minor($routeParams.majorMinorID);
}
);
我正在解决的问题是major_minor.department 是外键。 TastyPie 返回一个完整的对象,因此它不仅仅是部门 URI。 dataService.departments 数组是该用户可用的所有部门的数组。如果您要将 Major_minor.department 与 dataService.departments[indexOfDepartment] 进行比较,它们将是相等的。
有什么想法为什么 ng-model 没有正确选择 ng-option 吗?我对 Angular/Restangle 的理解可能存在差距,因为这只是我使用两者的第二个项目。
最佳答案
Jack,我遇到了类似的问题,并通过调整 ng-options 解决了它
<select
ng-model='dataService.major_minor.department.id'
ng-options='d.id as d.name for d in dataService.departments'
name='department'
class='select2'
required>
</select>
然后,在发布到我的快速 ReSTful 服务之前,我更改了我的 Angular 服务,将 dataservice.major_minor.department 从对象更改为 ID。这应该为您提供通过有效负载中的线路传输的外键,而不是非规范化的对象。这是一个 Coffeescript 服务,因此与您采用的工厂方法略有不同。
save: (major_minor) ->
major_minor.department = major_minor.department?._id
@$http.post("/api/major_minor/", major_minor)
Angularjs 文档在 ng-options 部分讨论了这个问题:https://docs.angularjs.org/api/ng/directive/select
希望有所帮助,尤其是 future 遇到此问题的搜索者。
关于javascript - 将 ng-model 与 ng-options 结合使用,将 Restangular 与 AngularJS 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566454/