I am creating a web app in which i want to store userid and role in session through Angularjs
this is my Angularjs file
$http.get('/login.asmx/loginuser', {
params: {
log: $scope.log,
pm: $scope.pm,
password: $scope.password
}
})
.then(function (response) {
{
$scope.suc = response.data;
console.log(response.data);
if (response.data == 'success') {
console.log('success');
$window.location.href = "../welcomepage/welcometable";
}
else
{
console.log('nosuccess');
$window.location.href = "../Login/Index";
}
}
})
i need to store $scope.pm and $scope.log in my session and want to use the same on my welcome page
how to store and use sessions in angularjs?
You can use session storage or local storage for that, here is the example of session storage.
session storage or local storage will not work here in stack overflow
so refer given link.
Link
window.addCart = function($scope, $http, $window, $document){
var getValue = function(){
return $window.sessionStorage.length;
}
var getData = function(){
var json = [];
$.each($window.sessionStorage, function(i, v){
json.push(angular.fromJson(v));
});
return json;
}
$scope.images = getData();
$scope.count = getValue();
$scope.addItem = function(id){
var image = document.getElementById('img'+id);
json = {
id: id,
img: image.src
}
$window.sessionStorage.setItem(id, JSON.stringify(json));
$scope.count = getValue();
$scope.images = getData();
}
$scope.removeItem = function(id){
$window.sessionStorage.removeItem(id);
$document.
$scope.count = getValue();
$scope.images = getData();
alert('Removed with Success!');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="">
<div ng-controller="addCart">
<p>{{ count }}</p>
<div>
<img id="img16" src="http://placehold.it/351x350"/>
Add to Cart
</div>
<div>
<img id="img5" src="http://placehold.it/352x350"/>
Add to Cart
</div>
<div>
<img id="img32" src="http://placehold.it/353x350"/>
Add to Cart
</div>
<div>
<img id="img43" src="http://placehold.it/354x350"/>
Add to Cart
</div>
<hr />
<table>
<thead>
<td>Image</td>
<td>Options</td>
</thead>
<tbody>
<tr ng-repeat="data in images" id>
<td><img ng-src="{{ data.img }}"/></td>
<td>Remove Item {{ data.id }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
angular.module('cookieStoreExample', ['ngCookies'])
.controller('ExampleController', ['$cookieStore', function($cookieStore) {
// Put cookie
$cookieStore.put('myFavorite','oatmeal');
// Get cookie
var favoriteCookie = $cookieStore.get('myFavorite');
// Removing a cookie
$cookieStore.remove('myFavorite');
}]);
look on
Related
Below is my HTML code :
<div class="container-fluid">
<div class="jumbotron" id="welcomehead">
<br><br><br><br><br><br><br><br><br><br>
</div>
<div class="row">
<div class="col-md-12">
<h2>Welcome {{username }}, your Season total is {{total }}</h2>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3 id="slogan" >5 teams; 1 Goal</h3><br>
<img src="http://res.cloudinary.com/deji/image/upload/v1508887997/ymkit_ww8np1.jpg">
<img src="http://res.cloudinary.com/deji/image/upload/v1508888352/indkit_zop1gx.jpg">
<img src="http://res.cloudinary.com/deji/image/upload/v1508887290/chad2kit_fa3lrh.jpg">
<img src="http://res.cloudinary.com/deji/image/upload/v1508887718/fbg2kit_lzndap.jpg">
<img src="http://res.cloudinary.com/deji/image/upload/v1508888206/vgc_kit_hvpdz4.jpg">
</div>
</div>
Below is the javascript code for the html code:
'use strict';
angular.module('TNF.welcome', ['ngRoute', 'firebase'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/welcome',{
templateUrl:'welcome/welcome.html',
controller: 'WelcomeCtrl'
});
}])
.controller('WelcomeCtrl',['$scope','$firebaseAuth','CommonProp','$location','DatabaseService',
function($scope,$firebaseAuth, CommonProp,$location, databaseService){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
databaseService.users.child(user.uid).once('value', function(usersSnapshot){
var users = usersSnapshot.val();
var total = users.total;
$scope.username = user.email;
$scope.total = total;
}, function(err) {
console.log(err);
$scope.total = 0;
});
} else {
// No user is signed in.
$location.path('/home');
}
});
$scope.logout = function(){
firebase.auth().signOut().then(function() {
console.log('Signed Out');
$location.path('/home');
}, function(error) {
console.error('Sign Out Error', error);
});
};
MY Issue
My issue is that the {{username}} and {{total}} values, which are results of the firebase query do not show in the view once the page loads. However, the values show up once I leave the page and then return to the view. Does this mean that the HTML code loads faster than the firebase query can be resolved? If so, is there a way to make the page only load AFTER the firebase query is resolved?
you'll need to let angular know to run an update.
$scope.username = user.email;
$scope.total = total;
$scope.$apply();
I am attempting to use ng-repeat with AngularJS but I am not getting the result of my scope in my DOM. Can anyone see the issue? I have been trying to troubleshoot this for hours and hours now and "players" is always null.
Here is my html:
<body ng-controller="CoachCtrl" >
<div class="mdl-tabs mdl-js-tabs mdl-js-ripple-effect">
<div class="mdl-tabs__tab-bar">
Starks
Lannisters
Targaryens
</div>
<div class="mdl-tabs__panel is-active" id="coach" >
<p>Number of players {{ players.length }}</p>
<table class="table">
<tr>
<th>Firstname
</th>
<th>Lastname
</th>
<th>Tryout Date
</th>
</tr>
<tr ng-repeat="kid in players" >
<td>{{ kid.firstname }}
</td>
<td>{{ kid.lastname }}
</td>
<td>{{ kid.tryout_date }}
</td>
</tr>
</table>
</div>
</div>
and here is my js:
'use strict';
angular.module('myApp.coach', ['ngRoute', 'firebase'])
// Declared route
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/coach', {
templateUrl: 'coach/coach.html',
controller: 'CoachCtrl'
});
}])
// Home controller
.controller("CoachCtrl", ["$scope", "$firebaseAuth", "$location",
function($scope, $firebaseAuth, $location) {
var ref = new Firebase("https://intense-heat-2545.firebaseio.com");
var authData = ref.getAuth();
if(authData){
console.log("User is "+authData.uid+" and is logged in with "+authData.provider);
var league = new Firebase("https://intense-heat-2545.firebaseio.com/users/"+authData.uid+"/league");
league.on("value", function(snapshot){
console.log("League ID = "+snapshot.val());
var leagueVal = snapshot.val();
var playerlist = new Firebase("https://blahblah.firebaseio.com/"+leagueVal+"/players");
$scope.players = [];
$scope.players.push({firstname:'John', lastname:'B', tryout_date:'2015-11-30'});
$scope.players.push({firstname: 'Marty', lastname: 'B', tryout_date: '2015-12-01'});
playerlist.on("child_added", function(snapshot){
//console.log("players ="+snapshot.val());
var player = snapshot.val();
console.log("Firstname ="+player.firstname);
var first = player.firstname;
var last = player.lastname;
var tyd = player.tryout_date;
console.log('player data ='+first+last+tyd);
$scope.players.push({ firstname: first, lastname: last, tryout_date: tyd });
var len = $scope.players.length;
for (var i = 0; i < len; i+=1){
if (1 === len){
console.log("player name = "+$scope.players[i].firstname);
}
}
console.log("players len ="+$scope.players.length);
}, function(error){
console.log("Error getting player info: "+error.code);
});
console.log("players ="+$scope.players[1].firstname+" len= "+$scope.players.length);
}, function(error){
console.log("Erro ="+error.code);
});
} else {
console.log("User is not logged in.");
$location.path('/signin');
}
}
]);
Three things.
The with the regular Firebase SDK Angular doesn't know when to run $digest.
Use $firebaseArray() rather than manipulating your own.
Use resolve() in the router to inject the user with $firebaseAuth().$waitForAuth().
-
var rootRef = new Firebase("https://<my-firebase-app>.firebaseio.com");
var leagueRef = rootRef.child("users").child(authData.uid).child("league");
// read it one time
leagueRef.once('value', function(snap) {
var leagueVal = snapshot.val();
var playerList = rootRef.child(leagueVal).child("players");
// $firebaseArray() will synchronize child events into an array
// Each update will know how to update $digest as well, which
// will keep the view updated.
$scope.players = $firebaseArray(playerList);
});
Your controller code would be greatly simplified if you use resolve in the router.
.constant('FBURL', '<my-firebase-app>')
.service('RootRef', ['FBURL', Firebase)
.factory('Auth', function($firebaseAuth, RootRef) {
return $firebaseAuth(RootRef);
})
.factory('UserLeague', function(RootRef) {
return function(uid) {
var leagueRef = RootRef.child("user").child(uid).child("league");
var deferred = $q.defer();
leagueRef.once(function(snap) {
deferred.resolve(snap.val());
});
return deferred.promise;
}
})
.config(function($routeProvider) {
$routeProvider.when('/coach', {
templateUrl: 'coach/coach.html',
controller: 'CoachCtrl',
resolve: {
leagueVal: function(UserLeague, Auth) {
var authData = Auth.$getUser();
return UserLeague(authData.uid);
},
authData: function(Auth) {
return Auth.$waitForAuth();
}
}
});
})
.controller("CoachCtrl", function($scope, leagueVal, authData, RootRef) {
// no need to check for a user because authData is injected
// use the resolved leagueVal to create a ref
var playerList = RootRef.child(leagueVal).child("players");
// synchronize the players to an array
$scope.players = $firebaseArray(playerList);
});
I try to build new APP with ionic framework and Angularjs.
Now my problem is i cannot show the result from controller to view. I try open console.log(allposts); in my browser ans we show the result good.
But in view its not show any thing
allpost.html
<dive class="item itemfull" ng-repeat="post in allpost">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news"><div class="title" ng-bind-html="post.content"></div></div>
</div>
</div>
</div>
And the controller
myApp.controller('allpost', function($scope , $http , $stateParams , Allposts) {
var id = $stateParams.id;
$scope.post = Allposts.GetAllposts(id);
});
myApp.factory('Allposts',['$http', '$q',function($http,$q){
var allposts = [];
var pages = null;
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id="+id+"&status=publish",{params: null}).then(function (response) {
items = response.data.posts;
allposts = items;
console.log(allposts);
return items;
$ionicLoading.hide();
});
}
}
}]);
Where is error ?
try to change the code like this in controller and factory in js files
.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
var id = $stateParams.id;
Allposts.GetAllposts(id).then(
function (response) {
$scope.allPosts = response.data.posts;
});
})
.factory('Allposts', ['$http', '$q', function ($http, $q) {
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id=" +
id + "&status=publish");
}
}
}]);
the html file
<div class="item itemfull" ng-repeat="post in allPosts">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
</div>
</div>
</div>
</div>
It works for my test
I'm trying to create a sigle-page app that contains shop list, in every shop card is the link to another view that contains table with products.
A shop looks like:
shop = {
id: 1,
name: "foo",
description: 'bar',
products: [item1, itemn];
};
app.js:
angular
.module('lightpointTestApp', [
'ngCookies',
'ngRoute',
'ui.sortable'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.when('/products/:shopID', {
templateUrl: 'views/products.html',
controller: 'ProductsCtrl'
})
.otherwise({
redirectTo: '/'
});
});
Main.html view where are shop list:
<h3>Shop list</h3>
<div class="row shopsContainer" ui-sortable ng-model="shops">
<div class="col-lg-3 shopCard" ng-repeat="shop in shops">
<button class="btn close cardClose" ng-click="removeShop($index)">×</button>
<div class="cardNumber">{{ shops.indexOf(shop) + 1 }}</div>
<div class="cardHeader">{{ shop.name }}</div>
<div class="cardBody">
{{ shop.address }}<br />
{{ shop.hours }}<br />
View {{ shop.products.length }} products
</div>
</div>
</div>
<div class="row">
<input type="text" ng-model="newShop.name" placeholder="Shop name" class="col-lg-3" />
<input type="text" ng-model="newShop.address" placeholder="Shop address" class="col-lg-3" />
<input type="text" ng-model="newShop.hours" placeholder="Shop hours" class="col-lg-3" />
<button class="btn btn-primary col-lg-3" type="button" ng-disabled="!newShop.name || !newShop.address || !newShop.hours" ng-click="addShop()">Add Shop</button>
</div>
</span>
</div>
</div>
products.js - controller for products page
angular.module('lightpointTestApp')
.controller('ProductsCtrl', function ($scope, $routeParams, shops) {
$scope.shopList = shops;
$scope.shop = {};
$scope.getShop = function (id) {
for (var i = 0; i < $scope.shopList.length; i++) {
if ($scope.shopList[i].id === id) {
return $scope.shopList[i];
}
}
return null;
};
var shopID = $routeParams.shopID;
$scope.shop = $scope.getShop(shopID);
})
products.html where is the table with products
<h2>{{ shop.name }}</h2>
<table class="table table-hover">
<tr>
<th>Product Name</th>
<th>Product Description</th>
</tr>
<tr ng-repeat="product in shop.products">
<td> {{ product.name }} </td>
<td> {{ product.description }} </td>
</tr>
</table>
The problem is that products.html doesn't bind with products.js and show something like {{shop.name}} and an empty table.
P.S. I think that products.js isn't correct, but I tried everything to do it well.
Thanks.
You have a parameter shops in ProductsCtrl, but there is nothing that will pass a value for it, so it is going to be null. You set the value of $scope.shopList to it, and then try to iterate over a NULL array, so you get an exception.
You can store the values of shops in a service, and then pass them around your app via injection. You can initialize their values within main.js, or within the service itself, and then the values will be available if you inject them into ProductsCtrl, something like
angular.module('lightpointTestApp')
.controller('ProductsCtrl', ['$scope', '$routeParams', 'shopsService',
function ($scope, $routeParams, shopsService) {
$scope.shopList = shopService;
$scope.shop = {};
$scope.getShop = function (id) {
for (var i = 0; i < $scope.shopList.length; i++) {
if ($scope.shopList[i].id === id) {
return $scope.shopList[i];
}
}
return null;
};
var shopID = $routeParams.shopID;
$scope.shop = $scope.getShop(shopID);
}]);
shopsService could look something like
angular.module('lightpointTestApp')
.service('shopsService', function() {
return [
// add whatever fields you need here from code in main.js
{ name: 'shop1', address: 'addr1' },
{ name: 'shop2', address: 'addr2' }
];
});
Where are your shop objects coming from? You are passing in shop, in products.js but not referencing it in the code. You should also use $q to use promises for async data. Also use the filter() function rather than a for loop to find the shop by shopId.
Are you hitting an API with shops or storing a local json for now?
With angular, you should separate your data logic manipulation in a factory or service as such:
productService.js
angular.module('lightpointTestApp')
.factory('shopService',function($http, $q){
var shops = [];
return {
getShops: function () {
var deferred = $q.defer();
$http.get('<path to product.json or api>').success(function(data){
shops = data;
deferred.resolve(data);
})
return deferred.promise;
},
getShopById: function(shopID) {
var deferred = $q.defer();
deferred.resolve(shops.filter(function(chain){
return chain.id === shopID;
})[0]);
return deferred.promise;
}
}
});
product.js
angular.module('lightpointTestApp')
.controller('ProductsCtrl', function ($scope, $routeParams, $q,shopService) {
$scope.shopList = [];
$scope.shop = {};
var shopID = $routeParams.shopID;
shopService.getShops.then(function(shops){
$scope.shopList = data;
})
$scope.getShopById = function(shopID) {
shopService.getShopById(shopID).then(function(shop){
$scope.shop = shop;
});
}
});
I'm developing a simple CRUD application with MEAN stack. So the scenario is a user post a data to the server and it will render the data in real-time. Everything works fine but whenever I refresh the page ,
It will sort of loads all the content, every time it tries to fetch the data. I guess this is a caching problem.
So what I want to achieve is, every time a user refresh the page or go to another link, the content will be there without waiting for split seconds.
Here's the link to test it on, try to refresh the page
https://user-testing2015.herokuapp.com/allStories
and the code
controller.js
// start our angular module and inject our dependecies
angular.module('storyCtrl', ['storyService'])
.controller('StoryController', function(Story, $routeParams, socketio) {
var vm = this;
vm.stories = [];
Story.all()
.success(function(data) {
vm.stories = data;
});
Story.getSingleStory($routeParams.story_id)
.success(function(data) {
vm.storyData = data;
});
vm.createStory = function() {
vm.message = '';
Story.create(vm.storyData)
.success(function(data) {
// clear the form
vm.storyData = {}
vm.message = data.message;
});
};
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
.controller('AllStoryController', function(Story, socketio) {
var vm = this;
Story.allStories()
.success(function(data) {
vm.stories = data;
});
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
service.js
angular.module('storyService', [])
.factory('Story', function($http, $window) {
// get all approach
var storyFactory = {};
var generateReq = function(method, url, data) {
var req = {
method: method,
url: url,
headers: {
'x-access-token': $window.localStorage.getItem('token')
},
cache: false
}
if(method === 'POST') {
req.data = data;
}
return req;
};
storyFactory.all = function() {
return $http(generateReq('GET', '/api/'));
};
storyFactory.create = function(storyData) {
return $http(generateReq('POST', '/api/', storyData));
};
storyFactory.getSingleStory = function(story_id) {
return $http(generateReq('GET', '/api/' + story_id));
};
storyFactory.allStories = function() {
return $http(generateReq('GET', '/api/all_stories'));
};
return storyFactory;
})
.factory('socketio', ['$rootScope', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
});
}
};
}]);
api.js (both find all object and single object)
apiRouter.get('/all_stories', function(req, res) {
Story.find({} , function(err, stories) {
if(err) {
res.send(err);
return;
}
res.json(stories);
});
});
apiRouter.get('/:story_id', function(req, res) {
Story.findById(req.params.story_id, function(err, story) {
if(err) {
res.send(err);
return;
}
res.json(story);
});
});
For api.js whenever I refresh the page for '/all_stories' or go to a '/:story_id' it will load the data for split seconds.
allStories.html
<div class="row">
<div class="col-md-3">
</div>
<!-- NewsFeed and creating a story -->
<div class="col-md-6">
<div class="row">
</div>
<div class="row">
<div class="panel panel-default widget" >
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span>
<h3 class="panel-title">
Recent Stories</h3>
<span class="label label-info">
78</span>
</div>
<div class="panel-body" ng-repeat="each in story.stories | reverse" >
<ul class="list-group">
<li class="list-group-item">
<div class="row">
<div class="col-xs-10 col-md-11">
<div>
<div class="mic-info">
{{ each.createdAt | date:'MMM d, yyyy' }}
</div>
</div>
<div class="comment-text">
<h4>{{ each.content }}</h4>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-3">
</div>
The loading problem you see is that the data is fetched after the view has been created. You can delay the loading of the view by using the resolve property of the route:
.when('/allStories', {
templateUrl : 'app/views/pages/allStories.html',
controller: 'AllStoryController',
controllerAs: 'story',
resolve: {
stories: function(Story) {
return Story.allStories();
}
}
})
Angular will delay the loading of the view until all resolve properties have been resolved. You then inject the property into the controller:
.controller('AllStoryController', function(socketio, stories) {
var vm = this;
vm.stories = stories.data;
});
I think you should use local storage. suited module - angular-local-storage
The data is kept aslong you or the client user clean the data,
Usage is easily:
bower install angular-local-storage --save
var storyService = angular.module('storyService', ['LocalStorageModule']);
In a controller:
storyService.controller('myCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService) {
localStorageService.set(key, val); //return boolean
localStorageService.get(key); // returl val
}]);
Match this usage to your scenario (for example - put the stories array on and just append updates to it)