0

i'm currently working on a back-end website in Angular with very little underscore.js. For my back-end i'm using the php-framework Laravel 4 which is very Handy. The problem i'm facing is :

When i query an url with angular the response is nice and clean so i can ng-repeat with no problem. But when i'm trying to extract the first element of the response with underscore, it gives me : undefined.

here's an extract of the code of my Controller:

var Client = $resource('myUrl/that/works/fine/and/returns/well');

var resultat = Client.query();

$scope.clients = resultat ;

$scope.isAnArray = _.isArray(resultat); // it returns true;

if i now try the line bellow $scope.myFirstElemInArray is undefined ???

$scope.myFirstElemInArray = _.first(resultat ); // expected:the first element.

I really don't see what's wrong with it. Here's the content of my variable resultat:

 [{"id":"2","email":"[email protected]"},{"id":"3","email":"[email protected]"}]

If somebody can give a little help, i'm really getting crazy with this Olivier (Fr)

1 Answer 1

3

You need to use callback for this i believe. Here is what the $resource documentation says

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most case one never has to write a callback function for the action methods.

something like

Client.query(function(data) {
$scope.myFirstElemInArray = _.first(data);
});
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.