Johnny
Johnny

Reputation: 9

Variables not updating outside function

So, I have two controllers (they have been reduced for simplicity) with one function each. The functions change a variable inside each of the controllers. The thing is, it looks like only the variable in the first controller is updated.

app.js

(function() {
  var app = angular.module('ScBO', []);
  var token = {};

  app.controller("LoginController", ['$http', function($http){
    this.userData = {};
    var lc = this;
    this.in = false;

    this.loginGo = function(){
      $http.post(<link>, <userData>)
      .then(function successCallback(response){
        token = response.data.access_token;
        lc.in=true;
      }, function errorCallback(response){
        lc.in=false;
      });
    };
  }]);

  app.controller("DashboardController", ['$http', function($http){
    var dsb = this;    
    this.totalLocals = 0;

    this.refresh = function(){
      $http.get('<link>?access_token='+token)
      .then(function successCallback(response){
        dsb.totalLocals = response.data.number_of_locals.number_of_locals;
      }, function errorCallback(response){
      });
    };
  }]);

})();

index.html

<body ng-controller="LoginController as loginCtrl">
  <div id="login-div" ng-hide="loginCtrl.in">
    <form ...>
   ...
    </form>
  </div>


  <div id="dashboard" ng-show="loginCtrl.in" ng-controller="DashboardController as dsb">
    <div class="numbers">
     <p>Number of Locals</p>
     {{dsb.totalLocals}}
    </div>
   </div>
</body>

So in the html, the first div appears in the beginning and not the second one. Then it hides and the second div shows up. This means that they are following the update of the loginCtrl.in variable. However, when I call the refresh function, it doesn't update the value in the last div.

I've tried with $scope and have been searching in here but I haven't been able to find a solution yet. Specially since the two controllers are equal but only one of them seems to be updating the variables normally.

Upvotes: 0

Views: 398

Answers (1)

Johnny
Johnny

Reputation: 9

So, I've figured out the problem. In the code above the error doesn't show as I only posted part of the code for simplicity, but I thought it was enough.

The thing was: I had the button that triggers the refresh function in a different div (like @leonardoborges ' plunkr). Like that two controllers are instantiated with their own values, something that I didn't know. The timeout function updates all instances of the controller, so that was confusing me.

So now I just put everything within one instance of the controller.

Upvotes: 0

Related Questions