1

I want to set hidden input value on login user then i want to get hidden input value in another page.

index.html (This page has hidden input )

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <script src="lib/ionic/js/ionic.bundle.js"></script>
    <script src="lib/ionic/ng-cordova-master/demo/www/lib/ngCordova/dist/ng-cordova.js"></script>
    <script src="cordova.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>

</head>
<body ng-app="starter">

    <input type="hidden" id="hiddenValue" ng-value="hiddenValue" />

    <ion-nav-view></ion-nav-view>
</body>
</html>

I set hidden input value then i use $location.path('/HomePage'); in order to redirect as below

Login.html's controller as below

.controller('LoginCtrl', function ($scope, LoginService, $ionicPopup, $state, $location) {
    $scope.data = {};

    $scope.login = function () {
        LoginService.loginUser($scope.data.username, $scope.data.password).success(function (data) {

            $scope.hiddenValue = "TestValue";  // I set value here           

            $location.path('/Menu');

        }).error(function (data) {
            var alertPopup = $ionicPopup.alert({
                title: 'Login failed!',
                template: 'Please check your credentials!'
            });
        });
    }
})

I can not display $scope.hiddenValue in Menu.html in below side.

.controller('MenuCtrl', function ($scope, LoginService, $ionicPopup, $state, $location) {

    alert($scope.hiddenValue);

})

when i try to use alert($scope.hiddenValue); in order to display value from hidden input , i get undefined error

Where i miss why i can not display value in another page ?

Soner
  • 1,280
  • 3
  • 16
  • 40

2 Answers2

3
<input type="hidden" id="hiddenValue" ng-value="hiddenValue" /> 

is not falling inside the scope of the loginCtrl.

$scope.hiddenValue = "TestValue"; statetment in the loginCtrl will assign TestValue to the $scope of LoginCtrl.

You can create a service "user" and have this.user == '';

.service('user', function () {
    this.user = '';

    this.setUser = function(name) {
        this.user = name;
    }
});

Inject this "user" service in controllers you need to share the name. And also set the value using the user.setUser('test') in your LoginCtrl controller.

Prabhas Nayak
  • 282
  • 1
  • 4
-1

It looks like you want to share data between controllers which is quite a common need. Looking at something like this might help you - AngularJS: How can I pass variables between controllers?

The best way is to use an AngularJS service or factory.

Community
  • 1
  • 1
scotney
  • 54
  • 4