Communicating between controllers in AngularJs

前端 未结 2 1138
说谎
说谎 2021-01-21 16:06

I have a simple question: what\'s the best (\'cleanest\', \'scaleable\') path one should go when it comes to interact between (let\'s say) two controllers. Would that be to defi

2条回答
  •  囚心锁ツ
    2021-01-21 16:31

    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

     
    Value in cntrl1: {{ myService.value }} 
    Value in cntrl2: {{ myService.value }} 

    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.

提交回复
热议问题