2014-04-02 180 views
0

我正在學習AngularJS。 我的服務:AngularJS資源

services.factory('Model', ['$resource', 
function ($resource) { 
    return $resource('model/:id', {}, {}); 
} 
]); 

services.factory('Department', ['$resource', 
function ($resource) { 
    return $resource('department/:id', {}, {}); 
} 
]); 

services.factory('Price', ['$resource', 
function ($resource) { 
    return $resource('price/:id', {}, {}); 
} 
]); 

我的控制器:

controllers.controller('SafeNewCtrl', ['$scope', '$location', 'Safe', 'Model', 'Department', 'Price', 
function ($scope, $location, Safe, Model, Department, Price) { 
    $scope.models = Model.query(); 
    $scope.departments =Department.query(); 
    $scope.prices = Price.query(); 

    // It doesn't work. console.log($scope.models[0] 'and other') = undefined. 
    $scope.safe = {model: $scope.models[0], department: $scope.departments[0], price: $scope.prices[0]}; 

    $scope.save = function() { 
     var safe = new Safe($scope.safe); 
     safe.$save(function() { 
      $location.path('list/f'); 
     }) 
    } 
} 
]); 

我有資源陣列每次查詢後()。 如何獲得正常的JSON作爲數組和數組的第一個對象設置爲$ scope.safe?

+0

電話是異步如此,因爲它們沒有獲得您需要使用響應處理程序來處理這個問題,因爲不幸的是$資源是如何工作的,這是不完全微不足道的,你不能立即訪問結果...在這種情況下使用$ http實際上更容易一些,因爲你得到了一個承諾,並可以使用$ q.all()來處理所有結果,然後我會嘗試寫出一些東西。 – shaunhusain

+0

啊只是檢查了文檔看起來你可以得到原來的承諾,所以會在下面猜測。 – shaunhusain

回答

1
controllers.controller('SafeNewCtrl', ['$scope', '$location', 'Safe', 'Model', 'Department', 'Price', '$q', 
function ($scope, $location, Safe, Model, Department, Price, $q) { 
    $scope.models = Model.query(); 
    $scope.departments =Department.query(); 
    $scope.prices = Price.query(); 

    $q.all([$scope.models.$promise, $scope.departments.$promise, $scope.prices.$promise]).then(function(){ 
     $scope.safe = {model: $scope.models[0], department: $scope.departments[0], price: $scope.prices[0]}; 
     console.log($scope.models[0]); 
    }) 



    $scope.save = function() { 
     var safe = new Safe($scope.safe); 
     safe.$save(function() { 
      $location.path('list/f'); 
     }) 
    } 
} 
]);