mercredi 29 juin 2016

How to share a $scope object between multiple controllers

I am facing problem while sharing a $scope object between 2 controllers.

In controller 'IssueBookCtrl',I am updating the books object element value like this.

$scope.books[i].issued = true;

Then I am using $emit service to share the $scope object with controller 'BookListCtrl_Librarian'.

$scope.$emit('update_parent_controller', $scope.books);

But when I run the view which is using the controller 'BookListCtrl_Librarian',i don't see the updated object.

controller.js

Controllers.controller('BookListCtrl_Librarian', ['$scope','$http','$location','$rootScope','BookData',
function ($scope, $http ,$location, $rootScope , BookData) {
    $http.get('data/books.json').success(function(data) {
    if($rootScope.books==='undefined'){
        $rootScope.books = BookData.getData();
    }
        $scope.books = data;
    });
    $scope.options = ['bookId', 'cost'];

    $scope.$on("update_parent_controller", function(event, books){
        $scope.books = books;
    });
    $scope.issue = function(bookId) {
        for (var i = 0, len = $scope.books.length; i < len; i++) {
            if ($scope.books[i].bookId == bookId) {
                $rootScope.book = $scope.books[i];
                break;
            }
        }
        $location.path('/issue/'+bookId);
    }
        $scope.return = function (bookId) {
            for (var i = 0, len = $scope.books.length; i < len; i++) {
                if ($scope.books[i].bookId == bookId) {
                    $rootScope.book = $scope.books[i];
                    break;
                }
            }
            $location.path('/return/'+bookId);
        }
    $scope.backToLogin = function() {
        $location.path("/main");
    }
    }]);
Controllers.controller('IssueBookCtrl', ['$scope','$rootScope','$http','$routeParams','$location',
function ($scope,$rootScope, $http, $routeParams, $location) {
    var Id=$routeParams.bookId;
    $http.get('data/books.json').success(function(data) {
        $scope.books = data;
    });
    $scope.issue = function(Id) {
        alert("issued");
       for (var i = 0, len = $scope.books.length; i < len; i++) {             
            if ($scope.books[i].bookId === Id) {
                $scope.books[i].issued = true;              
                $scope.$emit('update_parent_controller', $scope.books);
                $location.path('/home/librarian');
                break;
            }
        }
    }
}]);

Please guide me,any help is much appreciated.

Thanks

Aucun commentaire:

Enregistrer un commentaire