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 ?
<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.
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.
Related
Here is my app.js
var app = angular.module("app",[]);
app.controller("myFirstController",['$scope',function($scope){
$scope.test = "myfirstName";
$scope.test1 = "myfirstName";
}])
app.controller("mySecondController",['$scope','$rootScope',function($scope,$rootScope){
$scope.test = "myLastName";
//Here how to call my test,test1 scope using $rootScope ??
}])
Can i do this using $rootScope?I dont want to use any emit and broadcast or this
if you store any value in rootscope like :
$rootScope.test =" value ";
and you can retrieve value from the rootScope like
var value = $rootScope.test;
But it's not good to use for data maintenance and security
because if you refresh browser, then all scope values are cleared.
So I will suggest you for 3 varies ways
$cookies
$ngStorage
$Service
Broadcast
I dont want to use any emit and broadcast or
But that's the only way is best to pass value from one controller to another controller
you can do like below but use different names for avoiding errors in some cases.if you doesn't declare it as $rootScope in first ctrl then it will be undef in second ctrl
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body >
<div ng-controller="myFirstController">
</div>
<div ng-controller="mySecondController">
</div>
</body>
<script>
var app = angular.module('plunker', []);
app.controller("myFirstController",['$scope','$rootScope',function($scope,$rootScope){
$rootScope.test = "myfirstName";
}])
app.controller("mySecondController",['$scope','$rootScope',function($scope,$rootScope){
$scope.test = "myLastName";
console.log($rootScope.test);
//Here how to call my myFirstName scope using $rootScope ??
}])
</script>
</html>
I want to use this method (which ouputs a message if a user is typing) with a service. the method is updating a info varible (set its text to "typing" or blank).
I thought about using this method as a service to my angular model. the problem is that this method needs access to the text varible {{info}} with sits inside the view (some html).
How can I do that?
my code is below....
Thanks
js file
mymodule.controller("cntrlChat", ['$scope','isUserTypingService',
function($scope,isUserTypingService){
$scope.isUserTyping=function(){
isUserTypingService($scope.info);
}
}]);
mymodule.factory('isUserTypingService',['$q','$timeout', function($q,$timeout) {
var isUserTyping= function(info) {
runTwoFunctionWithSleepBetweenThem(function (){info='user is typing...';},function (){info='';},3500);
};
var runTwoFunctionWithSleepBetweenThem=function(foo1, foo2, time) {
$q.when(foo1()).then(() => $timeout(foo2, time));
}
return isUserTyping;
}]);
index.html
<html>
<head>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9">
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.1/angular-ui-router.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="../css/style.css">
</head>
<div ng-app="mymodule" ng-view>
</div>
</html>
chat.html
{{info}}
you could do something like this:
<input ng-model="userInput" ng-change="runWhenTyping()" />
in your controller:
$scope.userInput = '';
$scope.runWhenTyping = function () { isUserTypingService($scope.userInput) }
Each time they type runWhenTyping will be called and in turn it will call your service.
For some reason it gives me the error:
ReferenceError: random is not defined at Scope.$scope.generateRandom
I dont know what im doing wrong, you can go check out the website im using to do this HERE.
index.html:
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset="UTF-8" />
<title>Basic Login Form</title>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src = "https://rawgit.com/nirus/Angular-Route-Injector/master/dist/routeInjector.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
<script type="text/javascript" src="script23.js"></script>
</head>
<body ng-app = "app" ng-controller = "app">
<button ng-click = "generateRandom()">Generate Random Number</button>
<br> {{randomNumber}}
</body>
</html>
script23.js:
var app = angular.module('app', []);
app.service('random', function(){
var randomNum = Math.floor(Math.random()*10)
this.generate = function(){
return randomNum;
}
});
app.controller('app' , function($scope){
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
})
To use service in controller, you need to inject it.
app.controller('app', function ($scope, random) {
I'd recommend you to use following syntax:
app.controller('app', ['$scope', 'random', function ($scope, random) {
See Why we Inject our dependencies two times in angularjs?
Change your controller like this, since you are using the service 'random'
myApp.controller('app', ['$scope','random', function( $scope,random)
{
$scope.generateRandom = function(){
alert("Something")
$scope.randomNumber = random.generate();
}
}])
Here is the working Application
I'm new to App dev using AngularJs and PhoneGap, so I may be doing something wrong here (please rectify). My objective is to make the App exit if anyone presses the BackButton in Android when the /viewInitialDepartments is active (i.e. when the user is in that view). Relevant Codes are as follows :-
Of my index.html page:-
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width,height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" >
<meta http-equiv="x-ua-compatible" content="ie=10">
<meta name="msapplication-tap-highlight" content="no" >
<link rel="stylesheet" href="css/module-reset.css" ><link rel="stylesheet" href="css/module-grid.css" ><link rel="stylesheet" href="css/module-all.css" ><link rel="stylesheet" href="css/module-transitions.css"><link rel="stylesheet" href="css/module-custom.css" > <link rel="stylesheet" href="css/styleMenu.min.css">
<title>ad</title>
<script type="text/javascript" src="cordova.js"></script>
</head>
<body ng-cloak ng-app="askDadaApp">
<div id="mainBodyWrapper">
<div class="page {{ pageClass }}" ng-view></div>
</div>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.js"></script>
<script src="js/angular-animate.js"></script>
<script src="js/angular-touch.js"></script>
<script src="js/ngprogress.min.js"></script>
<link rel="stylesheet" href="css/ngProgress.css" >
<script src="js/script-controller.js"></script>
</body>
</html>
Of my Angular JS Contol Page (script-controller.js) :-
var adApp = angular.module('adApp',['ngRoute', 'ngAnimate','ngTouch','ngProgress']);
adApp.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {templateUrl: 'views/1-setconnection.html',controller: 'setController' })
.when('/viewInitialDepartments', {templateUrl: 'views/2-viewInitialDepartments.html',controller: 'viewInitialDepartmentsController' })
.when('/offLine', { templateUrl: 'views/1-offLine.html',controller:'offLineController'})
});
// CONTROLLERS
adApp.controller('offLineController', function($scope, $http, $location, $routeParams ) { $scope.pageClass = 'normal';var notOnlineToast = document.getElementById("notOnlineToast");notOnlineToast.style.display="block";
});
adApp.controller('setController', function($scope, $http, $location) {
var typeList = "CHECKCONNECTION";
$http.get("URL/php/fetchData.php?typeList=" + typeList )
.error(function(response) {$location.path('/offLine');
// if not offline then go to Home View (viewInitialDepartments)
$location.path('/viewInitialDepartments');
});
adApp.controller('viewInitialDepartmentsController', function($scope, $http, $location, $routeParams) {
var typeList = "CHECKCONNECTION";
$http.get("URL/php/fetchData.php?typeList=" + typeList )
.error(function(response) {
$location.path('/offLine');
});
// REST OF THE CODE
});
My config.xml file has the declaration :-gap:plugin name="org.apache.cordova.dialogs"
Now the thing is that I need to know how to make the App exit on pressing the BackButton on Android Phone while the user is in /viewInitialDepartments view. Please help. (Everything else is working fine as expected.)
EDIT - I guess this could be achieved using document.addEventListener("deviceready", onDeviceReady, false); and document.addEventListener("backbutton") but don't know how to do that in my present code as such that the backButton does what it does for all other views and just make the App close only when in /viewInitialDepartments view.
Define global variable to store current route(view) name
var CURRENT_ROUTE;
Assign value to CURRENT_ROUTE on route change
var adApp = angular.module('adApp',['ngRoute', 'ngAnimate','ngTouch','ngProgress']).run([
'$rootScope',
function ($rootScope) {
$rootScope.$on('$routeChangeStart', function (event, next) {
CURRENT_ROUTE = next;
});
}]);
Perform action on back button
document.addEventListener("backbutton", function(){
if(CURRENT_ROUTE === yourviewname){
navigator.app.exitApp(); // exit app
}
}, false);
I'm trying to learn Angular.js. I set up a simple page, in which I want to display a message from my script file. Here's the HTML structure:
<!DOCTYPE html>
<html ng-app>
<head>
<script data-require="angular.js#*" data-semver="2.0.0-alpha.31" src="https://code.angularjs.org/2.0.0-alpha.31/angular.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{message}}</h1>
</body>
</html>
And this is my script.js:
var MainController = function($scope){
$scope.message = "my message";
};
I'm supposed to see the words my message on the page, but instead I'm seeing literally {{message}}. I tried to wrap the JS code in self-envoking function:
(function() {
var MainController = function($scope) {
$scope.message = "my message";
};
}());
But it didn't have any result.
What am I doing wrong?
It's old syntax and you cannot declare controller like that. Now you need to register controller on your module.
angular.module('anyModuleName',[]).controller('yourControllerName',function(){
});
and also edit to ng-app="anyModuleName" where you initialize your app. In your case <html ng-app="anyModuleName">