【发布时间】:2016-11-04 12:59:31
【问题描述】:
我需要在两个控制器(控制器 A 和控制器 B)之间共享数据。我有一个服务来共享数据。但是,如果我使用视图中的“ng-model=shared.id”设置共享变量的值,那么控制器B可以看到控制器A设置的值;如果我在控制器 A 中设置共享变量,则控制器 B 看不到它。
app['controller']('controllerA', ['shared', function(shared){
//ControllerB will not see this for some reason, unless I set
//the value from the view using the ng-model=shared.id attribute.
shared['id'] = "123";
}]);
app['controller']('controllerB', ['shared', function(shared){
this['someId'] = shared['id'];
}]);
【问题讨论】:
-
好吧 - 你必须重新分配它!您没有传递对服务值的引用 - 您当时按原样传递它。
-
我不明白“按原样传递”。我是否应该创建另一个变量 this['id'] = "123" 然后将其分配给共享变量 (shared['id'] = this['id'])
-
请参阅下面的答案 - 基本上 - 当您更新共享变量时,使用该变量的任何内容也需要更新,不会自动获取更改。控制器中的含义是 - 当共享变量更新时,您必须调用
this['someId'] = shared['id'];。
标签: angularjs