AngularJS:如何等待$资源完成?

时间:2014-07-28 18:22:23

标签: angularjs

我有一个控制器:

app.controller('ProductDetailCtrl', ['$scope', '$q', '$resource', 'Product', function($scope, $q, $resource, Product) {
  $scope.product = {};

  $scope.init = function(id)
  {
    $scope.product = Product.get({productId: id});

  }

  $q.all([$scope.product.$promise]).then(function() {
    $scope.selected_color = $scope.product.products_colors[0];
  });

  // $scope.selected_color = $scope.product.products_colors[0];

}]);

还有一家工厂:

app.factory('Product', ['$resource', function($resource) {
  return $resource("/api/products/:productId", {}, {
    query: {method: 'GET', isArray: true},
  });
}]);

然而,当我加载页面时,它给了我:

Error: $scope.product.products_colors is undefined @http://localhost:3000/assets/products/controllers/productscontroller.js?body=1:11:5 qFactory/defer/deferred.promise.then/wrappedCallback@http://localhost:3000/assets/angular.js?body=1:11499:15 qFactory/ref/<.then/<@http://localhost:3000/assets/angular.js?body=1:11585:11 $RootScopeProvider/this.$get</Scope.prototype.$eval@http://localhost:3000/assets/angular.js?body=1:12609:9 $RootScopeProvider/this.$get</Scope.prototype.$digest@http://localhost:3000/assets/angular.js?body=1:12421:15 $RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:3000/assets/angular.js?body=1:12713:13 bootstrap/doBootstrap/<@http://localhost:3000/assets/angular.js?body=1:1420:9 invoke@http://localhost:3000/assets/angular.js?body=1:3919:7 bootstrap/doBootstrap@http://localhost:3000/assets/angular.js?body=1:1419:1 bootstrap@http://localhost:3000/assets/angular.js?body=1:1432:5 angularInit@http://localhost:3000/assets/angular.js?body=1:1345:5 @http://localhost:3000/assets/angular.js?body=1:21818:5 jQuery.Callbacks/fire@http://localhost:3000/assets/jquery.js?body=1:3100:1 jQuery.Callbacks/self.fireWith@http://localhost:3000/assets/jquery.js?body=1:3212:7 .ready@http://localhost:3000/assets/jquery.js?body=1:3424:3 completed@http://localhost:3000/assets/jquery.js?body=1:3454:3


return logFn.apply(console, args);

我怎么会等到$ resource完成加载?我想根据Product.get(..)的结果设置一个$ scope变量。我知道Product.get(..)正在返回并且使用products_colors属性进行对象,因为console.log是这样说的

1 个答案:

答案 0 :(得分:4)

使用回调:

Product.get({productId: id}, function(data) {
    $scope.product = data;
});