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

标签 javascript angularjs

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

相关文章:

javascript - 谷歌浏览器网络请求冲突?

javascript - 带 OR 运算符的 Angular 过滤器

javascript - 如何创建执行多重组合的函数?

angularjs - ng-option 过滤保留选择第一个值

javascript - Node/Express/Angular 服务器端外部 API 请求

javascript - .min.map javascript 源文件的正确 MIME 类型是什么?

javascript - React/Redux - 将新状态设置为一个数组状态

javascript - 未知提供商 : $resouceProvider <- $resouce

javascript - AngularJS 本地/全局范围变量的使用

angularjs - Angular 指令中的单向绑定(bind)