我有一个简单的书店示例,我正在为angularjs工作,我正在尝试将书籍ID从主页传递到编辑页面上的服务,以便可以呈现书籍详细信息。我发生的事情是,我可以看到当我的home' page with the correct book id being passed into the book service. However, I cannot seem to think of a way to have the
BookCtrl`在其他页面调用其余服务时加载该数据的其余调用。我期待的顺序是:
1) User enters a book ID to edit
2) User presses Search button
3) book.html page is loaded
4) BookEdit service is invoked with ID from Steps 1 and 2
5) ng-model for book loads data.
提前道歉,因为我从另一台计算机修改此代码时可能会出现一些错误,因此我无法复制/粘贴
代码如下:
home.html
<div ng-controller="HomeCtrl">
<div>
<label for="query">Book to edit</label>
<input id="query" ng-model ="editBook.query">
<button ng-click="loadBookById()">Search</button>
</div>
</div>
home.js:
var homeApp = angular.module('bookHome',['bookEdit']);
homeApp.controller('HomeCtrl',function($scope,$http,bookEditService)
{
$http.get('http://get/your/books/rest').success(function(data){
$scope.library = data;
});
$scope.editBook = {
query: '',
service:'bookEditService'
} ;
$scope.loadBookById = function()
{
$scope.$emit('loadBookById',{
query:$scope.editBook.query,
$service: $scope.editBook .service
}
$scope.$on('loadBookById', function(ev,search){
bookEditService.loadBook({
bookId: $scope.editBook.query
},
$scope.searchComplete,
$scope.errorSearching
);
});
$scope.searchComplete = function(results) {
$scope.results = results;
};
$scope.errorSearch= function(data,status,headers,config){
console.log(data);
// ...
};
}
book.html
<div ng-controller="BookCtrl" >
<div ng-model="details.title"></div>
<div ng-model="details.author"></div>
</div>
bookEdit.js
var bookEditApp = angular.module('bookEdit',[]);
bookEditApp.service('loadBook',function($http){
return{
loadBookById: function(params,success,error){
$http({
url: 'http://path/to/book/editing',
method: 'GET',
params:{bookId: params.bookId}).success(function(data,status,headers,config)
{
var results = data;
success(results || []);
}).error(function(){
error(arguments);
});
}
};
});
bookEditApp.controller('BookCtrl',function($scope){
$scope.details = {
title: "",
author: ""
};
});
答案 0 :(得分:2)
遵循您期望的顺序的替代方案是:
1)用户输入图书ID并按下按钮
2)HomeCtrl路由到EditCtrl,输入的id作为路由参数(不需要使用book服务):
app.controller('HomeCtrl', function ($scope, $location) {
$scope.editBook = function () {
$location.path('/edit/' + $scope.id);
};
});
3)加载EditCtrl,检索路由参数并询问图书服务是否有正确的书:
app.controller('EditCtrl', function EditCtrl($scope, $routeParams, bookService, $location) {
$scope.loading = true;
bookService.getBookById($routeParams.id)
.then(function (result) {
$scope.book = result;
$scope.loading = false;
});
4)当书籍被加载时,模型($scope.book
)被填充并且html被更新
这是一个有效的例子,希望能提供一些进一步的指导和想法:http://plnkr.co/edit/fpxtAU?p=preview