I have a text field:
<input type="text" ng-model="user">
and I have a button that will redirect to another page. On that page, I want to print the username typed in by the user. How can I do that?
My preference is ionic.
ionic works on top of angular. There are various ways by which you can achieve this functionality:
1) Use constants file to keep your value
Create a file called constants.js, include it in your index.html as:
<script src="Constants/Constants.js"></script>
declare key value pair combinations in it as:
var url_config = {
"USER_NAME" : "LOGIN_USER",
};
in your controller file, set the USER_NAME value as:
url_config.USER_NAME = $scope.user; //the model variable name that you had used
Use this value, where you want to access as:
$scope.loggedInUser = url_config.USER_NAME; // you will get the value here
The disadvantage here is that the value will get lost if you reload the screen. This can be ignored in android or ios app that you create using phonegap, the screens can't be refreshed, but if you are using web app this won't be a recommendable method.
2) Use a service to pass the constants
Create a utility service to keep the variable
angular.module('myApp').service('UtilityService', function () {
this.USER_NAME = '';
});
You can set this in your controller as:
angular.module('myApp')
.controller('LoginController', function ($scope, UtilityService) {
UtilityService.USER_NAME = $scope.user;
});
Access it in your other controller as:
angular.module('myApp')
.controller('UserController', function ($scope, UtilityService) {
$scope.loggedInUser = UtilityService.user;
});
This is a reliable way and a recommended method too.
3) Use local Storage
Here you can use the HTML5 feature of local storage to access the value from the browser's local storage.
Set the value in the login controller as:
angular.module('myApp')
.controller('LoginController', function ($scope, $localStorage) {
$localStorage.USER_NAME = $scope.loggedInUser;
});
In the receiving controller use it as:
angular.module('myApp')
.controller('UserController', function ($scope, $localStorage) {
$scope.loggedInUser = $localStorage.USER_NAME;
});
This will pertain the value even if the app goes to background or quits. Unless you clear the app cache or app data manually, the value will be saved.
For accessing $localStorage, you will require to use the ngStorage plugin that you can access from github and follow the instructions for instalation, then inject ngStorage as:
var myApp = angular.module('app', ['ngStorage']);
Now you are ready to use the $localStorage, provided you have included it in the controller where you are willing to access it.
4) Use session storage
Using the same ngStorage plugin you can use the session storage via $sessionStorage.
Set the value in the login controller as:
angular.module('myApp')
.controller('LoginController', function ($scope, $sessionStorage) {
$sessionStorage.USER_NAME = $scope.loggedInUser;
});
In the receiving controller use it as:
angular.module('myApp')
.controller('UserController', function ($scope, $sessionStorage) {
$scope.loggedInUser = $sessionStorage.USER_NAME;
});
Session storage keeps the data in session which gets expired after a limited time. This usage would be recommended for features like access tokens etc. For this scenario of username this won't be a recommended method
There are mainly two ways to achieve this:
1.By using Constants
app.js
angular.module('ionicApp', ['ionic'])
.constant('appConstant', {
user: ''
})
Controller
angular.module('ionicApp.home', ['ionic'])
.controller('homeCtrl', ['$state', 'appConstant', function($state, appConstant) {
'use strict';
$scope.user = '';
$scope.onClick = function() {
appConstant.user = $scope.user;
};
}]);
html
<input type="text" ng-model="user">
<button ng-click="onClick()">Submit</button>
Now you will get user name from any controllers by using appConstant.user
2.By using localstorage
Controller
angular.module('ionicApp.home', ['ionic'])
.controller('homeCtrl', ['$state', '$localStorage', function($state, $localStorage) {
'use strict';
$scope.user='';
$scope.onClick = function() {
$localStorage.set('user', user);
};
}]);
html
<input type="text" ng-model="user">
<button ng-click="onClick()">Submit</button>
Now you will get user name from any controllers by using $localStorage.get('user')
Related
i'm very much new to angular and trying to access localStorage. Here is the code. Please help me figure that out if it is not the right way to define and use. Thank you.
var app = angular.module("toggleApp", ['LocalStorageModule']).config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('test')
.setStorageType('localStorage');
});
app.controller("toggleController", function ($scope, $timeout,
timerParsingService, localStorageService) {
localStorageService.set('user' ,'yash');
you dont require to define any module or inject any other module in the application.
inject $window in your application and then you can access the localstorage module like this
angular.module('toggleApp', [])
.controller('toggleController', ['$scope', '$window', function ($scope, $window) {
$window.localStorage.setItem('ls', 'test');
}]);
and save the value like this
$window.localStorage.setItem('ls', 'test');
and you can retrieve the localStorage value like this
$window.localStorage.getItem('ls');
you could use ng-storge module and use
$localStorage.key = value or you could also use the getter and setter
$localStorageProvider.set('key', { k: 'value' });
I am using a service to get data from the server using $http.get() method. I am calling the function in the service and then accessing its variable from the controller. But it is not working this way.
The code is below
'use strict';
var mission_vision_mod = angular.module('myApp.mission_vision', ['ngRoute']);
mission_vision_mod.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/mission_vision', {
templateUrl: 'partials/mission_vision/mission_vision.html',
controller: 'mission_visionCtrl'
});
}]);
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope, $http, getMissionData) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getmissiondata();
$scope.missions = getMissionData.missiondata;
$scope.len = $scope.missions.length;
}]);
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
});
}
}]);
When i write the$http.get() function in the controller itself, it works. I am new to angular JS.
Try writing your service like this
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
this.getMissionData=function(){
return $http.get('m_id.json');
}
}]);
Use Service in controller like this:
mission_vision_mod.controller('mission_visionCtrl', ['$scope','getMissionData','$http', function($scope,getMissionData,$http) {
$scope.visiontext = "Here is the content of vision";
getMissionData.getMissionData().success(function(response){
$scope.missions=response;
$scope.len = $scope.missions.length;
}).error(function(errorl){
//handle error here
});
}]);
Also I suggest using a better name for service -'MissionDataService' :)
EDIT- Your sequence of injected service should match sequence of injectable names specified in the array..See my last edit
['$scope','getMissionData','$http',
function($scope, $http, getMissionData
The service names don't match with the variable names.
My advice: stop using this array notation. It clutters the code and is a frequent source of bugs. Use ng-annotate.
That said, your service is not correctly defined. It doesn't have any member function that would allow it to be called. Re-read the documentation of services. Defining services using factory() is easier than defining them using service(), BTW. And the service should return the promise returned by $http. Trying to access the value returned by an asynchronous call right after making the asynchronous call will never work. Read http://blog.ninja-squad.com/2015/05/28/angularjs-promises/
Try:
mission_vision_mod.service('getMissionData', ['$rootScope','$http', function($rootScope, $http){
var missiondata;
function getmissiondata(){
$http.get('m_id.json').success(function(data){
missiondata = data;
return missiondata;
});
}
}]);
I have a Controller which has something like this...
angular.module('kZoneApp').controller('DemandController', ['$http', '$scope', '$rootScope', 'dataFactory', '$window', '$routeParams','$sce', function ($http, $scope,$rootScope, dataFactory, $window, $routeParams,$sce) {
$scope.channel = $routeParams.channel;
now within my page.html, I want to do the following....
<script>
YoutubeVideoPlayer.openVideo('{{channel}}');
</script>
please note, I am using Routes, and page.html is loaded into my ng-view Via a Route.
<div id="myView" class="reveal-animation" ng-view></div>
I tried below code, but it returns undefined....
$().ready(function () {
var channel = angular.element("#myView").scope().channel
YoutubeVideoPlayer.openVideo(channel);
})
How can I get the value of Channel within my Template View?
Update
below works...but I am sure there has to be a cleaner solution
setTimeout(function () {
alert(angular.element("#myView").scope().channel)
}, 500);
A workaround solution should be creating a variable before your Angular.module definition.
var scopeInAngular = null;
and inside controller assign controller to your variable.
scopeInAngular = $scope;
then if you manipulate anything inside angular view use
scopeInAngular.$apply();
I am using angular-modal-service to show modal in my yeoman generated angular application. I'm following the documentation but got this error when passing data through inputs argument.
Error: [$injector:unpr] Unknown provider: userProvider <- user <-
targetModalCtrl
This is the function on controller where the modal is triggered
'use strict';
angular.module('webClientApp')
.controller('LogCreateCtrl', function ($scope, $rootScope, $log, $http, config, ModalService, $route) {
/*-- OTHER FUNCTIONS --*/
// record time in
$scope.recordTimeIn = function() {
// show target modal
ModalService.showModal({
templateUrl: "views/targetModal.html",
controller: "targetModalCtrl",
inputs: {
user: $scope.user.id
}
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {
$log.debug(result);
});
});
}
});
and this is the modal controller :
'use strict';
angular.module('webClientApp')
.controller('targetModalCtrl', ['$scope', 'user', function($scope, user) {
$log.debug(user);
}]);
The modal is showing fine if I'm not using the inputs arguments in LogCreateCtrl and remove the user in targetModalCtrl.
I'm not familiar with that angular-modal-service but I see two potential problems...
I'm not sure whether the modal service is robust enough to handle injection through the array notation (the docs aren't clear on this)
I don't see $log among the controller's parameters
You might try changing your controller to the following...
angular.module('webClientApp')
.controller('targetModalCtrl', function($scope, $log, user) {
$log.debug(user);
});
I see an issue that case cause the problem.
In inputs the value of user is $scope.user.id, now in controller, i am not able to see, user.id set anywhere in scope, which will mean undefined value assigned to user.
Modal service removes the undefined values and hence, is not able to inject user.
What is correct way of passing variables from web page when initializing $scope?
I currently know 2 possibilities:
ng-init, which looks awful and not recommended (?)
using AJAX request for resource, which requires additional request to server which I do not want.
Is there any other way?
If those variables are able to be injected through ng-init, I'm assuming you have them declared in Javascript.
So you should create a service (constant) to share these variables:
var variablesFromWebPage = ...;
app.constant('initValues', variablesFromWebPage);
With this service, you don't need to add them to the scope in the app start, you can use it from any controller you have, just by injecting it (function MyCtrl(initValues) {}).
Althouhg, if you do require it to be in the scope, then this is one of the main reasons what controllers are meant for, as per the docs:
Use controllers to:
Set up the initial state of a scope object.
Add behavior to the scope object.
Just add this cotroller to your root node:
app.controller('InitCtrl', function($rootScope, initValues) {
$rootScope.variable1 = initValue.someVariable;
$rootScope.variable2 = initValue.anotherVariable;
});
#Cunha: Tnx.
Here some more details how I did it:
In the Webpage:
<script type="text/javascript">
var variablesFromWebPage = {};
variablesFromWebPage.phoneNumber = '#Model.PhoneNumber';
</script>
In the angular application file, registering the service:
var module= angular.module('mymodule', ['ngRoute', 'ngAnimate']);
module.factory('variablesFromWebPage', function () {
return variablesFromWebPage
});
And then the controller:
module.controller('IndexController',
function ($scope, $location, $http, $interval, variablesFromWebPage) {
$scope.phoneNumber = variablesFromWebPage.phoneNumber;
}
);