0

I am trying to access an object from a controller inside another controller. For example:

Controller 1

MyApp.controller('workController', function ($scope) {

    $scope.xList = [
    {name:'test', type:'web', link:'test', image:'iso.jpg'},
    {name:'test', type:'web', link:'test', image:'iso.jpg'},
    ];

});

Controller 2: How to console.log an object from controller 1?

MyApp.controller('projectController', function ($scope) {
    console.log('$scope.xList[1]);
});

I tried $scope.workController.xList[1] too but didn't work.

Please help

2
  • Checkout rootScope for a way to communicate between controllers. It can broadcast messages with data across controllers that will listen. Commented Jun 23, 2015 at 0:58
  • possible duplicate of AngularJS Service Passing Data Between Controllers Commented Jun 23, 2015 at 1:03

2 Answers 2

2

The purpose of Angular controllers is to tie together view and services. For this reason, they're not really meant to talk to each other directly. If you need to communicate between controllers, you'd do it with a shared service.

MyApp.controller('workController', function($scope, SharedService){
    SharedService.set([
        {name:'test', type:'web', link:'test', image:'iso.jpg'},
        {name:'test', type:'web', link:'test', image:'iso.jpg'},
    ]);
});

MyApp.controller('projectController', function($scope, SharedService){
    console.log(SharedService.get());
});

MyApp.service('SharedService', function(){
    var self = {
        get: function(data){
            return self._data;
        },
        set: function(data){
            self._data = data
        }
    };

    return {
        get: self.get,
        set: self.set
    }
});
Sign up to request clarification or add additional context in comments.

Comments

2

Scope is defined per controller... In order to share data across controller you still have the option to use $scope.$parent or $rootScope to link controllers but I would use those carefully.

Angular Services are based on singleton patterns. You can also use those to share information between controllers and I think it will be the best approach.

I found that this has been previously discussed and here are some good examples:

AngularJS Service Passing Data Between Controllers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.