CaribouCode
CaribouCode

Reputation: 14398

How to share scope between same controller twice

I have a controller that appears in 2 locations on a page. For various reasons, this has to be the case.

So for example my simplified HTML structure is like this:

<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. 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. 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.

If I trigger the following from doing something in the aside, it doesn't update the main table.

var newRow = {
  _id: "1234213434",
  name: "Test",
  email: "[email protected]",
  accountType: "admin",
  logins: 0,
  created: new Date(),
  lastLogin: null,
  locked: false
};

$scope.userList.push(newRow);
$scope.tableParams.reload();

Upvotes: 2

Views: 887

Answers (2)

Ben Diamant
Ben Diamant

Reputation: 6206

"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

From angular's docs

When a Controller is attached to the DOM, Angular will instantiate a new Controller object

Meaning you can't share state among 2 controllers (like 2 instances of same class in java), what you can do is:

  1. Have a parent scope wrapping both scopes and use his scope to share data
  2. Use a shared service
  3. Broadcast messages between both controller (my least favored)

Upvotes: 3

Rasalom
Rasalom

Reputation: 3111

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

2) use $broadcast and $on: docs

Upvotes: 2

Related Questions