0

I have in my index.html two separate places where I declare:

<div ng-controller="ParentController>
    <div id="box1" ng-controller="SameController">
        Box1 {{test}} <button ng-click="changeMe()">Click</button>
    </div>

    <div id="box2" ng-controller="SameController">
        Box2 {{test}}
    </div>
</div>

Initially in SameController, $scope.test = "One" I want to make it so that when the user clicks the "Click" button, then {{test}} text will change to "Two" in both places (box1 and box2) (what the changeMe function does).

The problem is when I click, only the message in "Box1" changes to "Two", but not the message in "Box2". I tried using: $scope.$parent.test = "One" and make it so that SameController points to it, but it does not seem to work either.

How can I get around this so that both box1 and box2 change the text content of {{test}} when the button is clicked? The more elegant the solution the better.

C1pher
  • 1,933
  • 6
  • 33
  • 52
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • Why not just wrap box1 and box2 in the same element with SameController on it? – Pytth Jul 29 '15 at 17:36
  • Im simplifying the example, but the reason is because there are other controllers/directives, html that are in the middle, position styling applied that does not lend itself to wrapping both. – Rolando Jul 29 '15 at 17:40
  • possible duplicate of [Passing data between controllers in Angular JS?](http://stackoverflow.com/questions/20181323/passing-data-between-controllers-in-angular-js) – mikeswright49 Jul 29 '15 at 17:42
  • https://stackoverflow.com/questions/20181323/passing-data-between-controllers-in-angular-js you just use a service to share data between the two. – mikeswright49 Jul 29 '15 at 17:43

1 Answers1

0

Each element with ng-controller directive has its own scope, and they are not connected in any way. The most elegant solution is to set up a service for common application data.

app.value('commonData', {});    
app.controller('SameController', function ($scope, commonData) {
  $scope.data = commonData;
  $scope.changeMe = function () {
    $scope.data.test = 'test';
  }
});

And use it like this

<div ng-controller="ParentController>
<div id="box1" ng-controller="SameController">
Box1 {{data.test}} <button ng-click="changeMe()">Click</button>
</div>

<div id="box2" ng-controller="SameController">
Box2 {{data.test}}
</div>
</div>

You can also hold common data in parent scope, but it is not recommended because both SameController are forced to be direct descendants of the same parent directive this way.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565