user1852176
user1852176

Reputation: 455

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?

Upvotes: 0

Views: 92

Answers (1)

Hiten Patel
Hiten Patel

Reputation: 26

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.

Upvotes: 1

Related Questions