Communicating between controllers in AngularJs

前端 未结 2 1143
说谎
说谎 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

    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'
          });
    

提交回复
热议问题