我需要在 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/