30

I'm new to angular and I'm wondering how I can share a variable between controllers in angular. I'm using the following scripts -

In Main.js:

function MainCntl($scope) {
  ---code
}

function SearchCtrl($scope, $http) {
    $scope.url = 'http://10.0.0.13:9000/processAdHoc';
    $scope.errorM = "No results";     
    $scope.search = function() {

        $http.post($scope.url, { "data" : $scope.keywords}).
        success(function(data, status) {
            $scope.status = status;
            $scope.data = data;
            $scope.result = data; 
            alert('yes');
        })
        .
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;   
            alert('no');
            $scope.result = "failed";
        });
    };
}

In Index.html

<body ng-controller="MainCntl" >
---code
<div ng-controller="SearchCtrl">
     <form class="well form-search">
     <div class="ui-widget">
          <label for="tags"></label>
          <a ng-click="search()"><input type="image" src="../../images/search1.png" class="searchbox_submit" /></a>
          <input ng-model="keywords" placeholder="Shadow Search" id="tags" class="input-medium search-query rounded" /> 
     </div>
     </form>
</div>
---code
<p ng-model="result">
     {{result}}
</p>
</body>

Everything works well with the ajax I'm sending data and receiving a response, my question is as follows:

In the SearchCtrl function I have a variable called $scope.result that is later referred to in Index.html. If I insert the html code that contains that variable into the SearchCtrl controller it works fine but if it is in the MainCtrl controller it does not work. How can I share this variable between the controllers.

Thanks ahead

1 Answer 1

70

Use a service and inject it to both controllers and refer your scope vars to the services variable.

Example:

angular.module("yourAppName", []).factory("myService", function(){

  return {sharedObject: {data: null } }

});

function MainCtrl($scope, myService) {
  $scope.myVar = myService.sharedObject;
}

function SearchCtrl($scope, $http, myService) {
  $scope.myVar = myService.sharedObject;
}

In your template do:

{{myVar.data}}

See an example Uses Angular v1.1.5

The reason you put it in an inner object is to preserve your references, if you keep it without a "sharedObject", and change that object, your binding will be pointing to the old reference and wouldn't show anything in the template.

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

8 Comments

Hi ShaiRez, thanks for the quick answer and the example, but sadly it's still not working... maybe I am not implementing it correctly. I added everything you provided in the example and also changed the template to {{myVar.data}}. Two questions arise, shouldn't I change the templates view also, and also add myVar to the success/error functions of the ajax call? Thanks again, Gidon
After reading a bit more I found an easier way to do this with $rootScope... Thanks anyway for your time and kudos on the angular meetups, i'll try to make the next one :)
@ShaiRez is the preferred model for handling authentication? authenticate in a service (if not logged in already) and return a user model to all controllers that need it?
It's a different question and if I understand correctly than yes, use a login service or user service to hold communication or properties of that kind
@Gidon I edited the answer see the added example on jsbin. Also, there was an error in ShaiRez's code.
|

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.