简体   繁体   English

从没有rootScope的另一个控制器更改已经加载的控制器中的作用域值

[英]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. 我需要从controller-1更新一个controller-2(已加载)的$ scope值。 I don't want to use $rootScope. 我不想使用$ 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) $ emit(如果controller1是controller2的子代)
  • $broadcast (if controller2 is child of controller1) $ broadcast(如果controller2是controller1的子代)

If they are not in this relationship, then you need to: 如果他们不在这种关系中,那么您需要:

  1. emit from controller1 从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 在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. 在rootscope上使用brodcast并在范围上侦听。

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. 您可以使用$ localStorage更改该值。 or create one service for get and set that value. 或创建一个获取服务并设置该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 设置$ rootScope但值从另一个控制器不可见 - setting $rootScope but value then not visible from another controller Angularjs我可以从另一个控制器更改控制器的$ scope值吗? - Angularjs Can I change $scope value of a controller from another controller? 将rootScope值从一个控制器传递到另一个控制器 - Passing rootScope value from one controller to another controller 如何使用$ rootScope在另一个控制器的一个控制器中访问$ scope变量 - How to access $scope variable in one controller in another controller Using$rootScope 在离子的另一个控制器中更改$ scope的值 - change value of $scope in another controller in ionic 在不使用$ rootScope的情况下使用Angular路由更改控制器时如何更改范围 - How to change scope when controller is changed using Angular routes without using $rootScope 使用$ rootscope将变量从一个控制器传递到另一个控制器 - Passing variables from one controller to another with $rootscope 无法从其他控制器访问$ rootScope - Can't access $rootScope from another controller $ rootscope值在Controller中未定义 - $rootscope value undefined in Controller 从运行块我可以在另一个控制器而不是$ rootscope内调用角度范围函数 - From run block can i able to call angular scope function inside another controller instead of $rootscope
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM