1

I am trying to do a simple todo app with RESTful api. My restful service returns the below JSON,

[{"title":"completed this","completed":false},{"title":"and this too","completed":false}]

Returned as a application/json not a string.

My view is as below,

<div class="container" ng-app="todomvc">
        <div id="todoapp" ng-controller="TodoCtrl">
             <div class="row" ng-repeat="todo in todos">         
             {{todo.title}}
             </div>
        </div>
</div>

And I have the below JS code with controller and a factory,

var todomvc = angular.module('todomvc', []);

todomvc.factory('todoREST', function ($q,$http) {
 function get(){
   return $http.get('http://localhost/test.php');
 }
 return{get:get};
});

todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, $filter, todoREST) {
    var todos = $scope.todos = todoREST.get().then(function(data){
    todos = data.data;
    console.log(todos); // Data available here
    });
});

I am unable to get the title in the page when it is loaded. What am I doing wrong? And is my approach the right way to make a RESTful call?

Here is a link to what I have done, http://plnkr.co/edit/kaSCe9HoMPEK1hD4QgJl?p=preview

1 Answer 1

2

You're assigning $scope.todos to the promise returned by the service, not the data from the callback.

Try

todoREST.get().then(function(data){
    $scope.todos = data.data;
    console.log($scope.todos); // Data available here
});

http://plnkr.co/edit/C3fbK3NicU7XkdHAbzCr?p=preview

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, its working. I have defined put(todos) in a similar way but it is coming as undefined. plnkr.co/edit/zLNfrvkADtthowaJE98e?p=preview
You're still not really understanding the concept of promises I think. I don't understand where you get this double assignment from with services. var todos = $scope.todos = todoStorage.get()... The service returns a promise, not the todos. You can assign that promise to a variable but you probably don't want to.
Look at what your factory is returning to see why your put is undefined.

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.