Reputation: 1876
im new to AngularJS. I have this kind of program in Controller File.
.controller('AppCtrl', function($scope, $ionicPopup, $timeout, $ionicModal, $state, $http, $ionicLoading) {
var loginid;// globally Defined
$scope.ajaxLogin = function(){
loginid = 1;
}
$scope.myInfo = function(){
alert(loginid);
}
})
but everytime i call myInfo()
function Alert gives me : undefined
in my program ajaxLogin()
will call first. then if only button clicked myInfo()
will call and alert will be displayed. in Normal Javascript it work fine. but not sure how to work with angularjs.
ex :
var globalvarialbe;
function function1()
{
globalvarialbe=12;
}
function function2()
{
var local = globalvarialbe;
}
Upvotes: 0
Views: 3694
Reputation: 134
Yo need to attach the variable to $rootScope to make it globally available in AngularJS. This is how:
.controller('AppCtrl', function($scope, $rootScope, $ionicPopup, $timeout, $ionicModal, $state, $http, $ionicLoading) {
// Make sure you **inject $rootScope** first
$rootScope.loginid;
$scope.ajaxLogin = function(){
$rootScope.loginid = 1;
}
$scope.myInfo = function(){
console.log($rootScope.loginid); //Also, use console logs for better Dev Experience
}
})
Click here for more detailed documentation on HOW to use scopes and how NOT to.
Upvotes: 0
Reputation: 1876
I found an answer in another Forum.
just need to use $rootScope
$rootScope.loginid=1;
Upvotes: 0
Reputation: 1161
I have tested this code and it works just fine:
Controller:
angular.module('vars').controller('varsController', ['$scope', function($scope) {
var loginid;// globally Defined
$scope.ajaxLogin = function(){
loginid = 1;
};
$scope.myInfo = function(){
alert(loginid);
};
$scope.ajaxLogin();
}]);
HTML view:
<div ui-view ng-controller="varsController">
<button ng-click="myInfo()">Click</button>
</div>
Upvotes: 2
Reputation: 4047
The reason i was asking for more information Cade Lewis is because the way you had it should have worked perfectly fine.
.controller('AppCtrl', function($scope, $ionicPopup, $timeout, $ionicModal, $state, $http, $ionicLoading) {
var loginid;// globally Defined
$scope.ajaxLogin = function(){
loginid = 1;
}
$scope.myInfo = function(){
alert(loginid);
}
});
you can see its working here : http://plnkr.co/edit/tkpmS1vqsOjhUp8rA99Y?p=preview
However you are not supplicating the whole picture so its kind hard debugging you issue
Upvotes: 2