从另一个控制器角度js获取值

时间:2017-11-28 03:47:05

标签: javascript angularjs rootscope

我有问题。我想从rootScope.reslogin2传递到scope.user,但它不会显示在这里是我的js文件

    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);
}]);

我想在此段<p>Username : {{user}}</p>

中显示

1 个答案:

答案 0 :(得分:0)

来自 moncont 控制器的

user未与所需值同步,因此要修复它,您可以通过$scope.user = $rootScope.reslogin2;代替Object.defineProperty声明相应的getter :

&#13;
&#13;
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
      }
    });
  })
&#13;
<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>
&#13;
&#13;
&#13;