简体   繁体   English

在Angular.js中的组件/控制器之间访问对象

[英]Accessing objects between components/controllers in Angularjs

I need to share some objects between controllers in Angularjs and I have made something that works, but it just feels a bit clumsy to me. 我需要在Angularjs中的控制器之间共享一些对象,并且做出了一些行得通的事情,但对我来说却有点笨拙。 I'm wondering if what I have is acceptable, or if there's a preferred way to do so. 我想知道我所拥有的是否可以接受,或者是否有首选的方式可以做到。

In componentA I have an object that I want to access from componentB. 在componentA中,我有一个要从componentB访问的对象。

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

This works, but it just feels too complicated with a lot of back and forth communication. 这行得通,但是在进行大量来回通信时感觉太复杂了。 Is there anything built into Angular that is specifically designed to handle this kind of thing, or is what I have considered acceptable? Angular中是否有专门用于处理此类事情的东西,或者我认为可以接受的东西吗?

In my opinion $scope events should be used in cases where data changes are subscribed and not requested. 我认为$ scope事件应用于订阅但不请求数据更改的情况。

Instead you can use a service that will hold data and refer it in the controllers. 相反,您可以使用将保存数据并在控制器中引用它的服务。 Since services are singleton both the controllers will share the same instance and hence can easily share data. 由于服务是单例的,所以两个控制器将共享同一实例,因此可以轻松共享数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM