[英]How to share scope between same controller twice
I have a controller that appears in 2 locations on a page. 我有一个控制器显示在页面上的2个位置。 For various reasons, this has to be the case. 由于各种原因,必须如此。
So for example my simplified HTML structure is like this: 因此,例如,我的简化HTML结构是这样的:
<aside ng-if="aside.on" ng-controller="myController"></aside>
<div>Some other stuff</div>
<main ng-controller="myController">
<table ng-table="..."></table>
</main>
Now, when I do anything in the aside
, I expected to be able to use $scope
and for it to affect the main element because they use the same controller. 现在,当我在aside
做任何事情时,我希望能够使用$scope
并使其影响主要元素,因为它们使用相同的控制器。 But I've discovered that even though they use the same controller, they have different scopes. 但是我发现,即使它们使用相同的控制器,它们的作用域也不同。
So I'm wondering, if this is because the ng-if
, or if that's normal for the same controller in 2 locations. 所以我想知道,这是否是因为ng-if
,或者这对于2个位置的同一控制器是否正常? And also, how can I share the data between the 2 controllers. 而且,如何在两个控制器之间共享数据。 In particular, I am using ngTable
and need to add data to a table in main
, then refresh it when I edit something in the aside
. 特别是,我使用的是ngTable
,需要将数据添加到main
的表中,然后当我在aside
编辑某些内容时刷新它。
If I trigger the following from doing something in the aside
, it doesn't update the main
table. 如果我在aside
做某事而触发以下操作,则不会更新main
表。
var newRow = {
_id: "1234213434",
name: "Test",
email: "test@test.com",
accountType: "admin",
logins: 0,
created: new Date(),
lastLogin: null,
locked: false
};
$scope.userList.push(newRow);
$scope.tableParams.reload();
"I expected to be able to use $scope and for it to affect the main element because they use the same controller" is a wrong assumption “我希望能够使用$ scope并使其影响主要元素,因为它们使用同一控制器”是错误的假设
From angular's docs 从angular的文档
When a Controller is attached to the DOM, Angular will instantiate a new Controller object 当Controller附加到DOM时,Angular将实例化一个新的Controller对象
Meaning you can't share state among 2 controllers (like 2 instances of same class in java), what you can do is: 意味着您不能在2个控制器之间共享状态(例如java中相同类的2个实例),您可以做的是:
That's how controllers work, and you can't really do something with that. 这就是控制器的工作方式,而您实际上不能做任何事情。
Communication and data-sharing between controllers is quite common theme, basically you have 2 ways for that: 控制器之间的通信和数据共享是很常见的主题,基本上,您可以通过以下两种方式进行操作:
1) use service: Reused ng-controller as singleton 1)使用服务:将ng-controller用作单例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.