AngularJS资源

AngularJS资源,angularjs,Angularjs,我在学AngularJS。 我的服务: services.factory('Model', ['$resource', function ($resource) { return $resource('model/:id', {}, {}); } ]); services.factory('Department', ['$resource', function ($resource) { return $resource('department/:id', {}, {}); }

我在学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

调用是异步的,因此您无法立即访问结果,因为它们尚未获得。您需要使用响应处理程序来处理此问题,不幸的是,由于$resource的工作方式,这并不完全是微不足道的。。。在这种情况下使用$http实际上更容易一些,因为你得到了一个承诺,并且可以使用$q.all()来处理所有结果,不过我会尝试写一些东西。啊,只是仔细检查了文档,看起来你可以得到最初的承诺,所以下面将进行猜测。
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');
        })
    }
}
]);