Angular嵌套控制器初始化

时间:2016-08-18 15:10:55

标签: javascript angularjs

我有一个带有主控制器和子控制器的简单角度应用程序。 Maincontroller加载登录页面,成功登录后,使用子控制器加载欢迎页面。该应用程序很简单,正在运行。我的问题是在成功登录后设置登录用户名。

.controller('mainController', function($rootScope, $location, Auth) {

    var vm = this;
    vm.loggedinUser = Auth.getActiveUser();
    console.log(">>>>>>   ", vm.loggedinUser);

    //check to see user is logged in for every request made
    $rootScope.$on('$routeChangeStart', function() {
        vm.loggedIn = Auth.isLoggedIn();

    });

我的html页面很简单:

<body ng-app="bookapp" ng-controller="mainController as main">
..
<li class="navbar-text">Hello {{ main.loggedinUser }}! >

问题是不显示loggedinUser值。

1)为了使它工作,我必须在routechange监听器中初始化loggedinUser值。(将该行移动到监听器工作中)。为什么会这样?

2)另请注意,console.log语句在登录后以及显示欢迎页面时打印实际值。但是在应用程序加载本身(登录页面)期间,主控制器中设置了变量值,并且只能通过路由更改侦听器进行更改。在欢迎页面加载期间不会重新初始化它。

1 个答案:

答案 0 :(得分:0)

您可以将对象引用传递给控制器​​,也可以使用$ watch服务来评估每个摘要的getActiveUser函数并更新控制器范围。

&#13;
&#13;
angular.module("bookapp", []);

angular.module("bookapp").controller("mainCtrl", function(Auth) {
  var vm = this;
  vm.userData = Auth.data;
  vm.login = function() {
    Auth.data.loginTimeStamp = new Date();
    Auth.data.user = "TestUser";
  };
});

angular.module("bookapp").factory("Auth", function() {
  var data = {
    loginTimeStamp: null,
    user: null,
  };

  return {
    data: data
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>


<body ng-app="bookapp">

  <div ng-controller="mainCtrl as main">
    <p>Hello {{ main.userData.user }}!</p>
    <button ng-click="main.login()">Log In</button>
  </div>


</body>
&#13;
&#13;
&#13;

&#13;
&#13;
angular.module("bookapp", []);

angular.module("bookapp").controller("mainCtrl", function($scope, Auth) {
  var vm = this;
  $scope.getUser = Auth.getActiveUser;

  vm.login = function() {
    Auth.setActiveUser("TestUser");
    debugger;
  };
  $scope.$watch(function(scope) {
    return scope.getUser();
  }, function(newValue) {
    vm.loggedinUser = newValue;
    debugger;
  });
});

angular.module("bookapp").factory("Auth", function() {
  var data = {
    loginTimeStamp: null,
    user: null,
  };

  return {
    getActiveUser: function() {
      return data.user;
    },
    setActiveUser: function(userName) {
      data.user = userName;
    }
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>


<body ng-app="bookapp">

  <div ng-controller="mainCtrl as main">
    <p>Hello {{ main.loggedinUser }}!</p>
    <button ng-click="main.login()">Log In</button>
  </div>


</body>
&#13;
&#13;
&#13;