0

I have problem. I want to pass get from rootScope.reslogin2 to scope.user but it wont display here is my js file

    app.controller("logincont", ['$scope','$http','md5','$window','$rootScope',function($scope,$http,md5,$window,$rootScope){
     $scope.$watch('pass', function(val) {
          $scope.password = md5.createHash($scope.pass || '');
        });
    $scope.cari = function () {
            $http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
           $scope.reslogin  = response.data;
           $rootScope.reslogin2 = response.data[0].username;
           $scope.reslogin3 = response.data[0].lsmenu[0].idmenu; 
           console.log($scope.reslogin);
           console.log($scope.reslogin2);
      });
          };   

          }]);


    app.controller("moncont", ['$scope','$http','$filter','$rootScope',function($scope,$http,$filter,$rootScope){
      $scope.user = $rootScope.reslogin2;
      console.log($scope.user);
}]);

i want to display in this paragraph <p>Username : {{user}}</p>

Sunil Lama
  • 4,531
  • 1
  • 18
  • 46

3 Answers3

0

Make sure value is assigned before accessing it. In moncont controller keep $rootScope.reslogin2 in watch and assign it to $scope.user in watch function.

0

user from moncont controller not synchronized with desired value, so to fix it, you can for example, instead of $scope.user = $rootScope.reslogin2; declare corresponding getter via Object.defineProperty:

angular.module('app', [])
  .controller('logincont', function($rootScope, $scope, $timeout) {
    $scope.cari = function() {
      $timeout(function() {
        $rootScope.reslogin2 = ($rootScope.reslogin2 || 0) + 1;
      }, 1000)
    }
  })
  .controller('moncont', function($rootScope, $scope) {
    Object.defineProperty($scope, "user", {
      get: function() {
        return $rootScope.reslogin2
      }
    });
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app'>
  <div ng-controller='logincont'>
    <button ng-click='cari()'>Cari</button>
  </div>
  <div ng-controller='moncont'>
    user: {{user}}
  </div>
</div>
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
-1

Add the following method in your controller.

$scope.init = function(){
   $scope.user = $rootScope.reslogin2;
   console.log($scope.user);
}

Your template should be like following:

<div ng-controller="moncont" ng-init="init()">
    <p>Username : {{user}}</p>
</div>
Syedur
  • 414
  • 4
  • 10