JWDev
JWDev

Reputation: 856

AngularJS Accessing returned data from $resource in $scope

I have an API set-up, which delivers JSON data to $resource.

In my controller I am doing the following to query a specific row:

$scope.company = Companies.query({id: companyId});

However, if in my 'view' I then do:

{{ company.company_name }}

It doesn't show anything ... how do I assign the returned JSON data to the 'company' scope?

Upvotes: 0

Views: 237

Answers (2)

sch
sch

Reputation: 1388

This is how I use $resource

In Companyservice.js

this.queryItem = function (){

    var deferred = $q.defer();
    setTimeout(function() {
        // deferred.notify('Saving data..');
        var items = Company.query({},function() {
            deferred.resolve(items.d.results);
        }, function(error){
            deferred.reject(error);
        });
    }, 1000);
    return deferred.promise;
};

and in controller

var promise = CompanyService.queryItem();
    promise.then(function(response){
        // for each item in response, push item to array
        angular.forEach(response, function(item){
            $scope.companys.push(item);
        });

    }, function(reason){
        console.log(reason);
});

Instead of pushing the returned item(s) to an array, you should set $scope.company = response;

Hope this helps!

Upvotes: 1

Fraction
Fraction

Reputation: 463

First of all, have you tried to console.log Companies.query({id: companyId});

To verify the data is there? If so, you may fetch the data async. If so, unless it is wrapped in a $http you need to tell angular that the model has been updated so that the view can refresh, to do so just:

$scope.$apply();

Upvotes: 0

Related Questions