gpt4 book ai didi

javascript - 在 Angularjs 中访问组件/ Controller 之间的对象

转载 作者:行者123 更新时间:2023-12-03 06:07:44 25 4
gpt4 key购买 nike

我需要在 Angularjs 中的 Controller 之间共享一些对象,并且我已经制作了一些可行的东西,但对我来说有点笨拙。我想知道我所拥有的是否可以接受,或者是否有更好的方法来做到这一点。

在组件 A 中,我有一个想要从组件 B 访问的对象。

app.component("componentA", {
controller: function ($scope, $rootScope, $compile) {

//the object whose contents I want
$scope.objectToAccess = {name: 'object', value: 3};

//receives broadcast from componentB, returns the object
$rootScope.$on("getObject", function () {
$rootScope.$broadcast('receiveObject', $scope.objectToAccess);
});
}
}

app.component("componentB", {
controller: function ($scope, $rootScope, $compile) {

$scope.object = {name : null, value: null};

//receives the broadcast of the object and sets the value
$rootScope.$on("receiveObject", function (event,object) {
console.log(object);
$scope.object = object;
});

//broadcast to get the object contents
$rootScope.$broadcast('getObject');
}
}

这可行,但感觉太复杂了,需要大量的来回沟通。 Angular 中是否有内置的东西是专门为处理此类事情而设计的,或者我认为可以接受的东西?

最佳答案

在我看来,$scope 事件应该在订阅而不请求数据更改的情况下使用。

相反,您可以使用保存数据并在 Controller 中引用它的服务。由于服务是单例的,两个 Controller 将共享相同的实例,因此可以轻松共享数据。

关于javascript - 在 Angularjs 中访问组件/ Controller 之间的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39460076/

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