我想显示一个表格,其中包含与已编辑项目相对应的数据。我ui-router用于路由。我定义了一个状态:
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)的数据:
PropertyController
$scope.property
gapi.client.realestate.get(propertyId).execute(function(resp) { console.log(resp); });
我不知道是否可以使用,resolve因为数据是异步返回的。我试过了
resolve
resolve: { propertyData: function() { return gapi.client.realestate.get(propertyId).execute(function(resp) { console.log(resp); }); } }
第一个问题,propertyId是不确定的。您如何propertyId从那里得到url: "/properties/:propertyId"?
propertyId
url: "/properties/:propertyId"
基本上我想设置$scope.property在PropertyController向resp通过异步调用返回的对象。
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; } });
您需要阅读文档以解决问题。解析函数是可注入的,您可以使用$stateParams来从路由中获取正确的值,如下所示:
$stateParams
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; } }
最后,解析函数的值一旦解析即可注入您的控制器中:
myapp.controller('PropertyController', function($scope, propertyData) { $scope.property = propertyData; });