0

I have this situation : I have a webpage with two tabs. Those tabs need to use ng-view from angularjs. The particularity about those tabs is they need to use the same variable in reference, like referencing a variable in c# (ref keyword).

You can check the Using object section of this demo to know what I mean: http://plnkr.co/edit/zZfUQN?p=preview

<h3>Using object:</h3>
    <div class="example">
      <img class="mainImg" ng-src="{{mainImg.url}}" />
      <p>This is the parent scope with the main image.</p>
      <p>$scope.mainImg.url == {{mainImg.url}}</p>
      <div class="thumbs">
        <p>Thumbs generated with ng-repeat, with ng-click setting <strong>$scope.mainImg.url</strong> (click on them to see what happens):</p>
        <div class="thumbDiv" ng-repeat="img in images">
          <img class="thumb" ng-src="{{img}}" ng-click="mainImg.url = img" />
          <p>This is a child scope generated by ng-repeat.</p>
          <p>$scope.mainImg.url == {{mainImg.url}}</p>
        </div>
      </div>
    </div>

So, the main page is the main container and the tabs are the childs. How keep a variable as reference between those childs for using the same value between childs.

-- EDIT

I forget to mention something very important : The reference variable can be modified by a child and need the value need to be kept between others childs. Thank for your help,

Karine

Karine
  • 385
  • 1
  • 7
  • 18
  • 2
    Using `$rootScope` as in Clint's answer works fine. But for anything remotely complex I would create a service to hold shared state (and use resolve in the router if the value is retrieved via ajax). – Anthony Chu Nov 05 '14 at 22:11

1 Answers1

1

I think what you're after is $rootScope. Scopes also inherit, so if you define something in a parent scope and you don't override it in the child scope, you can access it.

function MainController($scope, $rootScope) {
    $rootScope.sharedVar = 'Hello';
}

function Child1Controller($scope, $rootScope) {
    //access $rootScope.sharedVar;
}

function Child2Controller($scope, $rootScope) {
    //access $rootScope.sharedVar;
}

EDIT as Anthony Chu mentioned, you could also create a service and inject it into any controllers that need the shared value.

Clint Powell
  • 2,368
  • 2
  • 16
  • 19