简体   繁体   中英

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. 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.

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?

In my opinion $scope events should be used in cases where data changes are subscribed and not requested.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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