简体   繁体   中英

Angularjs pass data in between services that exist on different pages

I have a simple book store example that I am working through for angularjs and I am trying to pass a book id from a home page into a service on an edit page so that the book details can be rendered. What I have happen is I can see the rest call being hit from my 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 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` load that data when a different page invokes the rest service. The order I am expecting is:

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.

Apologies in advance, there may be some errors as I was modifying this code from a different computer, so I couldn't copy/paste
code below:

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: ""
             };  
 });  

An alternative that follows the order you are expecting is:

1) User enters book id and presses button

2) HomeCtrl routes to EditCtrl with the entered id as a route parameter (no need to use the book service yet):

app.controller('HomeCtrl', function ($scope, $location) {

    $scope.editBook = function () {
      $location.path('/edit/' + $scope.id);
    };

  });

3) EditCtrl is loaded, retrieves the route parameter and asks the book service for the correct book:

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) When book is loaded the model ( $scope.book ) is populated and the html is updated

Here is a working example that hopefully will give some further guidance and ideas: http://plnkr.co/edit/fpxtAU?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM