Communicating between controllers in AngularJs

落花浮王杯 提交于 2019-12-01 23:53:52

Use service to share data between controllers

Your case is trying to share data between controllers, rather than watch service's value in controllers, I think directly reference service object to controller's scope is a better way

So your view can be

 <pre ng-controller="cntrl1">Value in cntrl1: {{ myService.value }} <button ng-click="update('value1')">Change to 'value1'</button></pre>

  <pre ng-controller="cntrl2">Value in cntrl2: {{ myService.value }} <button ng-click="update('value2')">Change to 'value2'</button></pre>

and change your controllers to

app.controller('cntrl1', function(myService, $scope) {
  $scope.myService = myService;
  $scope.update = function(str) {
    $scope.myService.setValue(str);
  }
});

app.controller('cntrl2', function(myService, $scope) {
  $scope.myService = myService;
  $scope.update = function(str) {
    $scope.myService.setValue(str);
  }
});

Use $broadcast/$emit

Just as @squiroid points out, you can use $broadcast to broadcast events to any controllers who is monitoring targeted events.

Please note here, you'd better not use $rootScope.$broadcast + $scope.$on but rather $rootScope.$emit+ $rootScope.$onas $broadcast event will bubble down through all descendant scopes, which might lead to serious performance problems.

This is the best way to communicate b/w the controller sharing same data via sevice but it is limited b/w controllers having the same service:-

Instead you can also choose to broadcast events that are captured by other controllers and change that data accordingly this way is more scaleable but not clean :-)

Sender ctrl :-
$rootScope.$broadcast('update', 'Some data'); //method that lets pretty much everything hear it even $scope too.

or

$rootScope.$emit('update', 'Some data');// only lets other $rootScope listeners catch it 

Listen Ctrl :-

   $rootScope.$on('update', function (event, data) {
        console.log(data); // 'Some data'
      });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!