0

I want to bind "Thread" and "Comments".

  • Thread 1
    • Comment 1
    • Comment 2
    • Comment 3
  • Thread 2
    • Comment 1
    • Comment 2
  • Thread 3
    • Comment 1
    • Comment 2
    • Comment 3
    • Comment 4
    • Comment 5

I have to fetch "Thread" and "Comment" from database by service. Thread Service gives data of all Threads while "Comment" service takes Thread ID and returns only passed Thread ID Comment.

So, How to bind the data like above nested list by tow separate services.

app.controller('ThreadCtrl', function ($scope, $http, $location) {
    $scope.Threads = [];
    $scope.Comments = [];

    $http({
        method: 'POST',
        url: 'api/ThreadList'
    }).success(function (data) {
        $scope.Threads = JSON.parse(data);
    });
   
    $http({
        method: 'POST',
        url: 'api/CommentList',
        data: JSON.stringify({ ThreadID: 0 }) //The problem is, ThreadID will resolve at runtime
    }).success(function (data) {
        $scope.Threads = JSON.parse(data);
    });
})

3
  • If you could please provide a sample JSON(i assume your services return JSON) of what both servicess return i might be able to help you out with your task Commented May 31, 2016 at 12:57
  • I also noticed that you save the data from both requests to $scope.Threads, i do think the seccond one should be saved to $scope.Comments. Commented May 31, 2016 at 12:58
  • In my opinion you should handle the desired format from backend as you will be needing nested comments array of objects inside a thread object. Handling it on the frontend is not recommended Commented May 31, 2016 at 13:02

1 Answer 1

1

Fetch the comments from server inside the success handler of your threads call:

app.controller('ThreadCtrl', function ($scope, $http, $location) {
    $scope.Threads = [];
    $scope.Comments = [];

    $http({
        method: 'POST',
        url: 'api/ThreadList'
    }).success(function (data) {
        $scope.Threads = JSON.parse(data);

        // iterate over the threads here (this is where they are available already) and fetch the comments by IDs...

        var thread = ...;

        $http({
            method: 'POST',
            url: 'api/CommentList',
            data: JSON.stringify({ ThreadID: thread.id })
        }).success(function (data) {
            thread.comments = JSON.parse(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.