简体   繁体   中英

change scope value in already loaded controller from another controller without rootScope

I need to update one $scope value of controller-2(already loaded) from controller-1. I don't want to use $rootScope.

Can I use broadcast or emit for same?

If the controllers are in a child-parent relationship, you can use:

  • $emit (if controller1 is child of controller2)
  • $broadcast (if controller2 is child of controller1)

If they are not in this relationship, then you need to:

  1. emit from controller1
  2. catch the event in the closest parent (could be the app)
  3. broadcast new event from this parent
  4. catch the event in controller2

Of course... this is not always the best way to go.

If you prefer, you can use other ways to communicate (eg use a common service).

Use brodcast on rootscope and listen on scope.

The best practice is to create a service for each custom event you want to listen to or broadcast.

.service("hiEventService",function($rootScope,$scope) {
this.broadcast = function() {$rootScope.$broadcast("hi")}
this.listen = function(callback) {$scope.$on("hi",callback)}

})

You can use $localStorage for change that value. or create one service for get and set that value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM