gpt4 book ai didi

javascript - 如何在多个 Controller 之间共享 $scope 对象

转载 作者:行者123 更新时间:2023-12-02 14:28:26 25 4
gpt4 key购买 nike

我在两个 Controller 之间共享 $scope 对象时遇到问题。

在 Controller “IssueBookCtrl”中,我正在像这样更新书籍对象元素值。

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

然后我使用 $emit 服务与 Controller “BookListCtrl_Librarian”共享 $scope 对象。

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

但是当我运行使用 Controller “BookListCtrl_Librarian”的 View 时,我没有看到更新的对象。

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;
}
}
}
}]);

请指导我,非常感谢任何帮助。

谢谢

最佳答案

嗨,你必须使用rootscope而不是范围发射

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

以及其他 Controller

 $rootScope.$on('update_parent_controller', function(event, books){
$scope.books = books;
});

关于javascript - 如何在多个 Controller 之间共享 $scope 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38045446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com