AngularJS资源

时间:2014-04-02 06:16:52

标签: 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?

1 个答案:

答案 0 :(得分: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');
        })
    }
}
]);