SherlockStd SherlockStd - 5 months ago 20
AngularJS Question

Need help on Angular Factory

Hi SO angular community !

I'm very confused, I think I have understand the factory purpose and concept, but seems not ...

Here is my problem (surely simple for you) :

I want to use my REST API (working perfectly) using Angular and .factory ...

rest.js

var app = angular.module('urlShortener', ['ngRoute', 'ngResource']);

app.factory('API', ['$resource',
function($resource){
return $resource('/link'});
}],{
get: {method:GET},
post: {method:POST},
put: {method:PUT},
delete: {method:DELETE},
}
);

app.controller('GetAll', function ($scope) {
$scope.links = API.get();
});


index.ejs

<div ng-controller="GetAll">
<ul>
<li ng-repeat="link in links">
<p>{{link.itemId}} --> {{link.url}}</p>
</li>
</ul>
</div>


Not working ... 2 hours I'm consulting the Angular API, and no solutions :/

Please help me I'm wasting time :'(

\\\\ SOLUTION ////

rest.js

app.factory('API', ['$resource', function($resource) { return $resource('/link'); }]);

app.controller('GetAll', ['$scope', 'API', function ($scope, API) {
API.query().$promise.then(function(links) {
$scope.links = links;
});
}]);

Answer

You can't just assign $resource instance to $scope.links, you need to do it when underlying promise resolves:

app.controller('GetAll', ['$scope', 'API', function ($scope, API) {
    API.get().$promise.then(function(links) {
        $scope.links = links;
    });
}]);