所以我得到了这个AngularJS控制器,我需要使用2种不同的服务Project
和Subproject
。一个通过project_id
字段链接到另一个。代码如下:
bonsControllers.controller('SubprojetDetailCtrl', ['$scope', '$routeParams', 'Project', 'Subproject',
function($scope, $routeParams, Project, Subproject) {
$scope.subproject = Subproject.queryFalse({projectId: $routeParams.id});
$scope.project = Project.queryFalse({projectId: $scope.subproject.project_id});
}]);
问题是当我在$scope.project
中使用或甚至在console.log上使用它时,$scope.subproject.project_id
的值未定义。
services.js代码是:
var bonsServices = angular.module('bonsServices', ['ngResource']);
bonsServices.factory('Project', ['$resource',
function($resource) {
return $resource(URL_API + '/projects/:projectId', {}, {
queryTrue: {method: 'GET', params: {projectId: ''}, isArray: true},
queryFalse: {method: 'GET', params: {projectId: ''}, isArray: false},
save: {method: 'POST', headers: {'Content-Type': 'application/json'}, isArray: false},
'delete': {method: 'DELETE', params: {projectId: ''}, isArray: false},
update: {method: 'PUT', params: {projectId: ''}, headers: {'Content-Type': 'application/json'}, isArray: false}
});
}]);
bonsServices.factory('Subproject', ['$resource',
function($resource) {
return $resource(URL_API + '/subprojects/:projectId', {}, {
queryFalse: {method: 'GET', params: {projectId: ''}, isArray: false}
});
}]);
模板代码是:
<div >
<span>Client :</span> {{project.client.name}} <br />
<span>Projet :</span> {{project.name}} <br />
<span>Sous Projet :</span> {{'Saison ' + subproject.saison}} <br />
<span>Type :</span> {{project.type}} {{subproject.project_id}}<br />
<span>Nature :</span> {{subproject.nature}} <br />
</div>
在Firebug中,我可以清楚地看到所有$ scope.subproject的元素,包括project_id
如果你们能给我一个关于这个问题的暗示,我会非常感激。由于
答案 0 :(得分:0)
当然,因为Subproject服务在那里有异步查询。当它完成后,它将返回一个承诺。
bonsControllers.controller('SubprojetDetailCtrl', ['$scope', '$routeParams', 'Project', 'Subproject',
function($scope, $routeParams, Project, Subproject) {
Subproject.queryFalse({projectId: $routeParams.id})
.then(function(subproject){
$scope.subproject = subproject;
return Project.queryFalse({projectId: $scope.subproject.project_id});
}).then(function(project){
$scope.project = project;
});
}]);
并且firebug记录所有元素的原因,因为它将记录对象的引用,然后控制台日志在查询完成时刷新对象数据。因此,在几毫秒内,数据未定义,并在查询完成时填充。
可以肯定的是,console.logged数据存在,只需编写$scope.subproject.project_id
答案 1 :(得分:0)
以下代码对我有用,它遵循康斯坦丁的回答:
bonsControllers.controller('SubprojetDetailCtrl', ['$scope', '$routeParams', 'Project', 'Subproject',
function($scope, $routeParams, Project, Subproject)
{
var project;
$scope.subproject = Subproject.queryFalse({projectId: $routeParams.id});
$scope.subproject.$promise.then(function(subproject){
project = Project.queryFalse({projectId: subproject.project_id});
$scope.project = project;
});
}
]);
你可能会看到$ promise.then为我做的伎俩。
谢谢