P.JAYASRI
P.JAYASRI

Reputation: 358

ng-init trigger a function at end of angularjs controller

I want to pass user name and id from php login page to angularjs controller onload . i tried it by ng-init to call basicDetails(username, id) . this function trigger at end of main controller. and also another problem passed parameter to angularjs variable print passed value in inside basicDetails function , outside it shows value as empty

<body  ng-controller="mainController" ng-init="basicDetails('<?php echo$_SESSION["username"];?> ','<?php echo$_SESSION["itmsNo"];?> ')">
<center>
    <div >
      <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b><br>
                <a href="reset-password.php" class="btn btn-warning">Reset  Password</a><br>
        <a href="logout.php" class="btn btn-danger">Sign Out</a>
    </div>   </center>
<!-- Main div showing different templates loaded by ng-view directive -->
<div class="container main"  ng-view>
</div>

Maincontroller.js

templeApp.controller('mainController', ['$scope','$rootScope','$http','webService', function($scope,$rootScope, $http,webService,user) {
    $rootScope.loggedUser;
    $scope.itmsNo;

    // This function trigger by ng-init , but called end of main controller 
    $scope.basicDetails = function(logedUser,itmsNo){
        $rootScope.loggedUser =logedUser;
        $scope.itmsNo =itmsNo;    
        console.log($scope.loggedUser );  // console print actual value          
    }
    console.log('..'+$scope.loggedUser );  // console print empty value

    $scope.user = webService.userData('impl/userData.php',$scope.loggedUser);

}]);

Upvotes: 0

Views: 235

Answers (1)

Dan
Dan

Reputation: 63059

As you said, ng-init runs after the rest of the controller code. This is why you get undefined when you try to log it outside of basicDetails. It hasn't been set yet because basicDetails sets it later.

So run all of your initialization code inside of basicDetails:

templeApp.controller('mainController'...
  $scope.basicDetails = function(logedUser, itmsNo) {
    $rootScope.loggedUser;
    $scope.itmsNo;

    $rootScope.loggedUser = logedUser;
    $scope.itmsNo = itmsNo;
    console.log($scope.loggedUser);

    $scope.user = webService.userData('impl/userData.php', $scope.loggedUser);    
  }
}}

You can rename it from basicDetails to something like init so it makes more sense.

Upvotes: 2

Related Questions