A
A
Artur Bekerov2014-11-16 18:37:13
JavaScript
Artur Bekerov, 2014-11-16 18:37:13

How to use factory data in Angular?

Greetings.
have the following code inside the controller

$scope.billings = Billing.query();

$scope.getTotalAmount = function(index){
//тут посложнее логика
            return $scope.billings[index].bills;
        }

When calling getTotalAmount() on the page, an error appears:
Can't interpolate: 
                                            {{getTotalAmount()}}
                                            
TypeError: Cannot read property 'bills' of undefined

Obviously, the data did not have time to come, but is already being requested.
I assume that promises are needed, but I can't use them.
I also tried .then and $watch, also get different errors.
send, please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2014-11-16
@krekerov

If you use promises, then you can do this:

$scope.getTotalAmount = function(index){
    //тут посложнее логика
    if(!$scope.billings.$resolved)
        return 0;
    return $scope.billings[index].bills;
}

But this will not help if an error occurred during the request (promise rejected).
You can do this:
$scope.getTotalAmount = function(index){
    //тут посложнее логика
    if(!$scope.billings[index])
        return 0;
    return $scope.billings[index].bills;
}

A
Alexander Sydorenko, 2014-11-16
@San40

You have getTotalAmount function(index)
Let me explain. getTotalAmount , when called, expects you to pass it an index by which it can return $scope.billings[index].bills to you. If you do not pass index to the view by simply calling {{getTotalAmount}} instead of {{getTotalAmount(2 or any index by which you can get this is your $scope.billings[index].bills)}} you will naturally get an error, since index in your case undefined, and $scope.billings[undefined] God himself ordered to be undefined for such inputs. Well, js in general, and angular in particular, cannot guess what kind of data you expect from external approximate signs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question