我有一个角度控制器,用$资源(例如/ rest / book)实例化,它运行正常。
我想让控制器使用另一个$资源(例如/ rest / recommendedTitle),我不知道如何使用。
这就是我的控制器目前的样子:
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
};
});
答案 0 :(得分:3)
相关资源始终可以在工厂中组合在一起。
dashboard.factory("Post", function($resource) {
return {
books:$resource("/rest/book/:id"),
recommendedTitles:$resource("/rest/recommendedTitles")
};
});
然后在控制器中,可以使用资源:
Post.books.query()
Post.recommendedTitles.query()
答案 1 :(得分:2)
就像你已经做的那样,让另一家工厂创建一个新的$resource
并将其注入你的控制器:
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;
});
};
});