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

1
  • 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). Commented Nov 5, 2014 at 22:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.