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

Raymond the Developer
  • 1,576
  • 5
  • 26
  • 57
  • Checkout [rootScope](https://docs.angularjs.org/api/ng/service/$rootScope) for a way to communicate between controllers. It can broadcast messages with data across controllers that will listen. – area28 Jun 23 '15 at 00:58
  • possible duplicate of [AngularJS Service Passing Data Between Controllers](http://stackoverflow.com/questions/17952620/angularjs-service-passing-data-between-controllers) – Dalorzo Jun 23 '15 at 01:03
  • Got it to work.Thanks! – Raymond the Developer Jun 24 '15 at 16:28

2 Answers2

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

Community
  • 1
  • 1
Dalorzo
  • 19,834
  • 7
  • 55
  • 102
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
    }
});
Aaron Cicali
  • 1,496
  • 13
  • 24