0

I'm learning AngularJS. My services:

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', {}, {});
}
]);

My controller:

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');
        })
    }
}
]);

I got array of Resources after each query(). How can I get normal JSON as array and first objects of arrays to set to the $scope.safe?

2
  • The calls are async so you can't immediately access the results since they haven't been obtained you need to use the response handlers to handle this, unfortunately because of how $resource works this isn't entirely trivial... using $http in this case is actually a bit easier because you get a promise back and could use $q.all() to take care of all the results I'll try to write something up though. Commented Apr 2, 2014 at 6:22
  • Ah just double checked the docs it appears you can get the original promise so will be guessing below. Commented Apr 2, 2014 at 6:25

1 Answer 1

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');
        })
    }
}
]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.