Pregunta

I am experimenting with the fabulous Restangular library, and I have run into some trouble when trying to return some JSON objects and bind them to the $scope object.

I have this function inside my Factory script, which essentially is just returning a list of blogs utilising the Restangular.getList() function.

angular.module("ecmaworld").factory("Authenticate", function(Restangular) {
// Testing Function
var Blogs = Restangular.all("blogs");
return {
    blogs: function() {
        Blogs.getList("blogs").then(function(blogs) {
            return blogs;
        }, function(error) {
            console.log(error);
        });
    }
};});

The Factory method here returns the a list of blog posts. I then attempt to call this function which I ahve defined in the Factory script and utilise it in one of my controller scripts like this:

angular.module("ecmaworld").controller("LoginController", function($scope, Authenticate) {

//Testing function
$scope.getBlogs = function() {
    $scope.blogs = Authenticate.blogs();
};
});

When I attempt to use the "data-ng-repeat" directive to loop through all the blogs posts, I do not get anything displaying. I can see that teh API method has worked through google developers as the http response returns the JSON objects. However, I am unsure to why they are not displaying when attempting to loop through them in the VIEW. If you could please assist me, that would be much appreciated. I am only new to Angular, so go easy guys.

Thanks.

¿Fue útil?

Solución

The blogs() method needs to return the promise...

blogs: function() {
    return Blogs.getList("blogs").then(function(blogs) {
        return blogs;
    }, function(error) {
        console.log(error);
    });
}

And then assign the result to the scope property when the promise is resolved...

$scope.getBlogs = function() {
    Authenticate.blogs().then(function (blogs) {
        $scope.blogs = blogs;
    });
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top