1

Sendind data between controllers use Service. But what better? Use $on at controller and $broadcast at service; Or simply javascript Object? (Exp:

myapp.factory('MyService', function(){
    var obj = {};

    return{
        setObject: function(value){
            obj.value = value;
        },

        getObject: function(){
            return obj;
        }
    };
});
Geray Suinov
  • 3,521
  • 3
  • 16
  • 19
  • What is your actual use case? – Wottensprels Aug 21 '14 at 07:16
  • @Sprottenwels I have search controller with can search by 3 instance. That controller has 'Search' button and tabs which choose searched instance. Another - Instance1Controller may generated view for searched list. So I may exchange data between controllers. – Geray Suinov Aug 21 '14 at 07:20
  • @Sprottenwels and global question: at what situation use each method?)) – Geray Suinov Aug 21 '14 at 07:22

1 Answers1

1

you can exchange data between two controllers by using same service example:

myapp.controller('myController', ['$scope','MyService'
function ( $scope,myService) {
   var obj={};
   obj=myService.setObject();
   $scope.obj=obj;
}]);

myapp.controller('myController2', ['$scope','MyService'
function ( $scope,myService) {
   var obj2={};
   obj2=myService.setObject();
   $scope.obj2=obj2;
}]);

 myapp.factory('MyService', function(){
    var obj = {};

    _setObject = function (value) {
      obj.value = value;
      return obj;
    }

    _getObject = function () {
        return obj;
    }

    return {
        setObject : _setObject ,
        getObject :_getObject 
    }
});

controllers contains the reference of service object when one controller change the object the other controller object automatically get changed because they shared the same reference of that service object

Geray Suinov
  • 3,521
  • 3
  • 16
  • 19
malik rizwan
  • 102
  • 9
  • I know that, but I asked what method more better – Geray Suinov Aug 21 '14 at 07:41
  • 1
    this is better because $broadcast and $on starts event bubbling and creats more $watches which slows the perfomance and not easy to manage . and secondly angular also say use minimum $on and broadcast as possible for more http://stackoverflow.com/questions/11252780/whats-the-correct-way-to-communicate-between-controllers-in-angularjs – malik rizwan Aug 21 '14 at 07:53