我想显示一个包含与编辑项目对应的数据的表单。我用 ui-router
用于路由。我定义了一个状态:
myapp.config(function($stateProvider) {
$stateProvider.
.state('layout.propertyedit', {
url: "/properties/:propertyId",
views : {
"contentView@": {
templateUrl : 'partials/content2.html',
controller: 'PropertyController'
}
}
});
在
PropertyController
, 我要设置 $scope.property
来自以下调用(Google Cloud Endpoints)的数据: gapi.client.realestate.get(propertyId).execute(function(resp) {
console.log(resp);
});
不知道能不能用
resolve
因为数据是异步返回的。我试过 resolve: {
propertyData: function() {
return gapi.client.realestate.get(propertyId).execute(function(resp) {
console.log(resp);
});
}
}
第一期,
propertyId
未定义。您如何获得 propertyId
来自 url: "/properties/:propertyId"
?基本上我想设置
$scope.property
在 PropertyController
到resp
异步调用返回的对象。编辑:
myapp.controller('PropertyController', function($scope, , $stateParams, $q) {
$scope.property = {};
$scope.create = function(property) {
}
$scope.update = function(property) {
}
function loadData() {
var deferred = $q.defer();
gapi.client.realestate.get({'id': '11'}).execute(function(resp) {
deferred.resolve(resp);
});
$scope.property = deferred.promise;
}
});
最佳答案
您需要阅读 the docs for resolve .解析函数是可注入(inject)的,你可以使用 $stateParams
从您的 route 获取正确的值,如下所示:
resolve: {
propertyData: function($stateParams, $q) {
// The gapi.client.realestate object should really be wrapped in an
// injectable service for testability...
var deferred = $q.defer();
gapi.client.realestate.get($stateParams.propertyId).execute(function(r) {
deferred.resolve(r);
});
return deferred.promise;
}
}
最后,解析函数的值一旦解析就可以注入(inject)到 Controller 中:
myapp.controller('PropertyController', function($scope, propertyData) {
$scope.property = propertyData;
});
关于angularjs - Angular ui-router 通过解析获取异步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18004298/