HJW
HJW

Reputation: 23443

Can an Angular controller have multiple $resource?

I have an angular controller that is instantiated with a $resource (e.g. /rest/book) and it is working fine.

I'm thinking of allowing the controller to work with another $resource (e.g. /rest/recommendedTitle) and i am not sure how.

This is how my controller currently looks like:

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

dashboard.factory("Post", function($resource) {
    return $resource("/rest/book/:id");
});

dashboard.controller("DashboardCtrl", function($scope, Post) {
    // handle retriving a list
    Post.query(function(data) {
        $scope.books = data;
    });

    // user selected on a book
    $scope.bookSelectionListener = function(book) {
        $scope.selectedBook = book;

        console.log("Selected book id: " + $scope.selectedBook.bookId.S);

        console.log("Going to fetch similar titles which is in another table based on the book id");

         // call another $resource restful api to get recommended title
    };
});

Upvotes: 1

Views: 783

Answers (2)

Chandermani
Chandermani

Reputation: 42669

Related resources can always be grouped together in factory.

dashboard.factory("Post", function($resource) {
    return {
           books:$resource("/rest/book/:id"),
           recommendedTitles:$resource("/rest/recommendedTitles")
    };
});

And then in controller, resource is available to be used:

Post.books.query()
Post.recommendedTitles.query()

Upvotes: 3

Florian F.
Florian F.

Reputation: 4700

Well just like you already did, have another factory creating a new $resource and inject it in your controller :

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

dashboard.factory("Post", function($resource) {
    return $resource("/rest/book/:id");
});

dashboard.factory("Whatever", function($resource) {
    // you should probably initialize some particular method depending on your backend here
    return $resource("/rest/whatever/:id");
});

dashboard.controller("DashboardCtrl", function($scope, Post, Whatever) {
    // handle retrieving a list
    Post.query(function(data) {
        $scope.books = data;
    });

    // user selected on a book
    $scope.bookSelectionListener = function(book) {
        $scope.selectedBook = book;

        console.log("Selected book id: " + $scope.selectedBook.bookId.S);

        console.log("Going to fetch similar titles which is in another table based on the book id");

         // call another $resource restful api to get recommended title

         Whatever.query({bookId : book.id}, function(data) {
             $scope.similarBooks = data;
         });

    };
});

Upvotes: 2

Related Questions