Login details not going in localStorage - javascript

I am making a test Web app and I am trying to store my user details in the local storage but Some how, Its not storing in the local Storage which in turn makes my login to fail or there may be any other reason. I am not getting any errors in the console and when I sign up the data is also going into my database.
Code for my Controller:
`(function(){
angular.module('Test')
.controller('loginController',["$scope","$state","$http", function($scope, $state, $http){
if(localStorage['User-Data']) {
$scope.loggedIn = true;
}
else {
$scope.loggedIn = false;`}
$scope.logUserIn = function() {
$http.post('api/users/login', $scope.login).success(function(response){
localStorage.setItem('User-Data', JSON.stringify(response));
$scope.loggedIn = true;
}).error(function(err){
console.log(err);
});
};
$scope.logOut = function() {
localStorage.clear();
$scope.loggedIn = false;
}
}]);
})();
and my Html is as follows:
<nav class="nav navbar-default navbar-fixed-top" ng-controller="loginController">
<div class="container-fluid">
<div ng-show=!loggedIn>
<strong> Email: </strong> <input type="text ng-model="login.email">
<strong> Password: </strong> <input type="password" ng-model="login.password">
<button ng-click="logUserIn()"> Login </button> <a ui-sref="signUp"> Create an Account </a>
</div>
<div ng-show="loggedIn">
<a ui-sref="editProfile"> Edit Profile </a>
<a ui-sref="logOut()"> Logout </a>
</div>
</div>
</nav>
<body>
<div ui-view> </div>
</body>
The problem is not about any syntax error or missing directory. Please look into this code and help me out.

Try to use
JSON.parse(localStorage.getItem('User-Data'))

change your code from
localStorage.setItem('User-Data', JSON.stringify(response));
to
localStorage.setItem('User-Data', JSON.stringify(JSON.parse(response)));

Related

ng-submit is not working in Laravel PHP framework

everyone, I have another question related to Laravel/AngularJS.
In my mini-project, I have form which user can post question in the form, but when I click submit button, there are no requests (from inspect in Google Chrome). However, I have a Log in interface, the button is working very well. I use the same logic, same html structure. And I am wondering how can I fix this problem.
I have been debugging this for 2 hours, have been Googling for a long time. Please help me out!!
Below are the codes.
// Add question page
<script type="text/ng-template" id="question.add.tpl">
<div ng-controller="QuestionAddController" class="question-add container">
<div class="card">
<form name="question_add_form" ng-submit="Question.add()">
<div class="input-group">
<label>Title</label>
<input type="text"
name="title"
ng-minlength="5"
ng-maxlength="255"
ng-model="Question.new_question.title"
required>
</div>
<div class="input-group">
<label>Description</label>
<textarea type="text"
name="desc"
ng-model="Question.new_question.desc">
</textarea>
</div>
<div class="input-group">
<button ng-disabled="question_add_form.$invalid"
class="primary"
type="submit">Submit</button>
</div>
</form>
</div>
</div>
</script>
// Service and Controller
.service('QuestionService', [
'$http',
'$state',
function ($http, $state) {
var me = this;
me.new_question = {};
me.go_add_question = function () {
console.log(1);
$state.go('question.add');
};
me.add = function () {
if (!me.new_question.title)
return;
$http.post('/api/question/add', me.new_question)
.then(function (r) {
console.log('r', r);
// if (r.data.status) {
// console.log(r.data);
// me.new_question = {};
// $state.go('home');
// }
}, function (e) {
console.log('e', e);
})
}
}
])
.controller('QuestionAddController', [
'$scope',
'QuestionService',
function (QuestionService, $scope) {
$scope.Question = QuestionService;
}
])
in QuestionService.add(), there is no "return value" (console.log('r', r);) in my browser.
I make sure routes and url are working fine by directly typing the address in browser. Any suggestion will be highly appreciated!
Thanks in advance!!!
Edit:
Besides, the button Add Question is not working, too. I have to use ui-sref to make it redirect to the target url, will this be the reason why the submit button is not working (like I use ui-sref not the ng-submit to redirect)
// Add question
<div class="navbar clearfix">
<div class="container">
<div class="fl">
<div class="navbar-item brand">somethingHere</div>
<form ng-submit="Question.go_add_question()" id="quick_ask" ng-controller="QuestionAddController">
<div class="navbar-item">
<input ng-model="Question.new_question.title" type="text">
</div>
<div class="navbar-item">
<button ui-sref="question.add" type="submit">Add question</button> <!--ui-sref="question.add"-->
</div>
</form>
</div>
<blablabla something not important here!!!!>
Your injections in the controller is the wrong order. Should be
.controller('QuestionAddController', [
'$scope',
'QuestionService',
function ($scope, QuestionService) {
$scope.Question = QuestionService;
}
])
EDIT:
The ordering itself does not really matter, but the controller function argument ordering must match the ordering in the array. E.g.
Correct:
['QuestionService', 'Service2', '$scope', function(QuestionService, Service2, $scope) { ...
Incorrect:
['QuestionService', 'Service2', '$scope', function(QuestionService, scope, Service2) { ...
The reason to define the controller with array is so that the code can be minified

update variable in another controller in AngularJS

okay, so I am building a web-app using angular.js. I have started to implement user authentication.
I did this with it's own controller:
app.controller("userControl", ["$http", "share", function($http, share){
this.login = {};
var user = this;
this.doLogin = function(){
this.login.fn = "login";
$http.post('classes/main.php', user.login).success(function(data){
console.log(data.Error);
if(data.Error == undefined){
alert("Success");
share.user = data;
window.location.href = "#memberHome";
}
});
}
}]);
and I have a member's page with it's own controller:
HTML:
<div id="memberHome" data-role="page" ng-controller="member-Ctrl as member">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<p class="navbar-brand" href="#">Calendar</p>
</div>
<ul class="nav navbar-nav navbar-left">
<li>Overview</li>
<li>Friends</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span class="glyphicon glyphicon-user"></span> Logged in as: {{member.user.forename + " " + member.user.surname}}</li>
<li><span class="glyphicon glyphicon-log-in"></span> Log Out</li>
</ul>
</div>
</nav>
<div data-role="content">
<calendar selected="day"></calendar>
</div>
</div>
javascript:
app.controller("member-Ctrl", ["share", function(share){
this.user=share.user;
}]);
I need the User controller to tell the member controller the details of the new user.
I googled this and looked at the answers of a similar question, which led me to This
and i created a service as shown in the video:
app.service("share", function(){
this.user = {}
});
Now whenever i login and get redirected to the memberHome page, it tells me Logged in as:
Can anybody see why this might be?
I am very new to Angular, and am learning, just about, everything when I need it.
I should probably say that i am using jQuery Mobile (for a multi-page document) and Bootstrap 3
You can use a service to share information between controllers or use the $rootScope
var app = angular.module('mymodule',[]);
app.controller('Controller1', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showImages = true;
}]);
app.controller('Controller2', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showImages = false;
}]);
And in the template:
<div ng-controller="Controller1">
<div class="images" ng-show="$root.showImages"></div>
</div>

AngularJS view not updating

I'm trying to make my first AngularJS application and I've run into a problem.
I have an input:
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
A button:
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
and an expression:
{{ activeUser }}
I want the text to change to whatever was typed in the input once the button is clicked. For that I have the following controller:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.activeUser = "Test";
$scope.setActiveUser = function() {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
};
}]);
The initial value "Test" is shown just fine and according to the console the value of "activeUser" is being changed correctly as well. But the text in the view stays the same.
I have seen similar questions where a $scope.$apply() was the answer, but if I add that after the console.log I get
"Error: [$rootScope:inprog] $apply already in progress".
What am I missing here?
EDIT:
I have noticed that If I put the input, button and expression in the same HTML file it all works fine. However my Input and button are in a navbar in index.html while the expression is in view1.html
This is the body of index.html:
<body ng-app="myApp.view1">
<nav class="navbar navbar-inverse navbar-fixed-top" ng-controller="View1Ctrl as view">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#/view1">Kwetter</a>
</div>
<div class="navbar-collapse collapse" >
<ul class="nav navbar-nav">
<li>Home</li>
<li>Profile</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="password" class="form-control">
</div>
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
</form>
</div>
</div>
</nav>
<div id="pagewrapper" class="container">
<div ng-view></div>
<div>Angular seed app: v<span app-version></span></div>
</div>
and this is my view1.html
<div ng-controller="View1Ctrl as view">
<!-- row 1: welcome -->
<div class="row">
<div class="col-md-12 pull-left">
<image ng-src="{{ view.users[0].avatar }}"/>
<!-- If I put the button and input here it will work -->
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
{{ activeUser }}
</div>
</div>
<!-- row 2: main content -->
<!-- left the rest of the content out because it would just clutter the page -->
I tried placing the ng-controller in <div id="pagewrapper" class="container"> instead of the first div of view1.html, but that made no difference.
I think u have misplaced the button or textbox or expression,
note : these should be inside the ng-controller.
please try this, it will work
<html>
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="View1Ctrl">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
{{activeUser}}
</div>
<h1>Hello Plunker!</h1>
</body>
</html>
script.js code
var app = angular.module("app",[]);
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.activeUser = "Test";
$scope.setActiveUser = function() {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
};
}]);
refer http://plnkr.co/edit/ixbByBQ9nGm4XEqEFi4t?p=preview
You have the properties directly on $scope and that is breaking the binding. Instead try:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userInfo = {
userNameLogin: "",
activeUser:"Test"
}
$scope.setActiveUser = function() {
$scope.uesrInfo.activeUser = $scope.userInfo.userNameLogin;
console.log($scope.activeUser);
};
}]);
and in your view:
{{userInfo.activeUser}}
From Egghead.io https://egghead.io/lessons/angularjs-the-dot
Within your code I can't see anything causing the problem. I made a fiddle, that shows that your code works:
http://jsfiddle.net/xxvsn8xs/
You need to declare the ng-appand the ng-controller of course, like in the fiddle, to let the app work at all.
Also, an view update might not occur, if setting the activeUser actually occurs outside of the angular scope, which might be within an external library or whatever. It is true, that these could be achieved by calling $scope.$apply() directly, but it is nor recommended, as the digest might already be in progress. This is the case in your code, as why you get the according error message.
Instead use angulars $timeout service with a callback and 0 delay, that applies the value to $scope.activeUser. $timeout will check, if a digest cycle is in progress and if not, will start one.
$scope.setActiveUser = function() {
$timeout(function () {
$scope.activeUser = $scope.userNameLogin;
console.log($scope.activeUser);
});
};
Don't forget to define $timeout in your controllers dependencies:
app.controller('View1Ctrl', ['$scope', '$timeout', function($scope, $timeout) {
Angular watches the variable you bind to $scope, but if you replace that variable Angular is not able to detect it. That's why $apply would be a suggestion.
Another suggestion is to bind the variable to a 'model' variable:
app.controller('View1Ctrl', ['$scope', function($scope) {
$scope.userNameLogin = "";
$scope.myData = { activeUser: "Test" };
$scope.setActiveUser = function() {
// Angular will pick up the change in the myData object, and will update all variables attached to it
$scope.myData.activeUser = $scope.userNameLogin;
console.log($scope.myData.activeUser);
};
}]);
view:
{{ myData.activeUser }}
Do you execute your application in Apache ? I'd the same issue when I was using file:// And I fixed my issue by using a localhost.
I put my navbar (containing the input and button) in a partial and made a new directive for it. Instead of placing the navbar in the index.html I put it in the individual partials and now it works fine. I suspect the problem had something to do with different scopes.
navbar html:
<a class="navbar-brand" href="#/view1">
Kwetter
<image id="navbar-image" src="src/kwetter_logo.png"/>
</a>
</div>
<div class="navbar-collapse collapse" >
<ul class="nav navbar-nav">
<li>Home</li>
<li>Profile</li>
</ul>
<form class="navbar-form navbar-right">
<div class="form-group">
<input ng-model="userNameLogin" type="text" placeholder="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="password" class="form-control">
</div>
<button ng-click="setActiveUser()" type="submit" class="btn btn-success">Sign in</button>
</form>
</div>
</div>
the directive:
app.directive('navbar', function() {
return {
restrict: 'E',
templateUrl: 'partials/navbar.html',
controller: 'View1Ctrl as view'
}
});
Then I just added <navbar></navbar> to every view where I want a navbar.
Thanks everyone, your help pushed me in the right direction.

AngularJS, only runs correctly in firefox why?

I'm using angularjs. The example I have done works perfectly in firefox, but does not work any other browser.
The error that appears in other browsers when I press add picture botton in index is:
XMLHttpRequest cannot load file:///C:/...../gifwallet/add_gif.html. Cross origin requests are only supported for HTTP.
I do not understand is what is wrong.
index.html
<html lang="es" ng-app="gifwalletApp">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="stylesheets/app.css">
<script src="javascripts/angular.js"></script>
<script src="javascripts/angular-translate.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="src/app.js"></script>
<script src="javascripts/ui-bootstrap-tpls-0.11.0.min.js"></script>
<title>GIF Wallet</title>
</head>
<body>
<div class="container">
<div ng-controller="TranslateController">
<button ng-click="changeLanguage('es')" translate="BUTTON_TEXT_ES"></button>
<button ng-click="changeLanguage('en')" translate="BUTTON_TEXT_EN"></button>
</div>
<header ng-controller="MenuController">
<ul class="nav nav-pills pull-right">
<li class="active">
<a href="#">
<span class="glyphicon glyphicon-home"></span>
<span class="badge pull-right">42</span>
</a>
</li>
<li>
<span class="glyphicon glyphicon-plus"></span>
</li>
<li>
<span class="glyphicon glyphicon-search"></span>
</li>
</ul>
<h3 class="text-muted">GIF Wallet</h3>
</header>
<div id="images" class="row" ng-controller="gifListController">
<div class="col-lg-12 media" ng-repeat="gif in giflist">
<a href="" class="pull-left thumbnail">
<img class="media-object" src="{{ gif.url }}">
</a>
<div class="media-object">
<h4 class="media-heading">{{ gif.name }}</h4>
<p>
<a><span class="glyphicon glyphicon-minus"></span> {{ 'FAVORITO' | translate }}</a>
</p>
<p>
<a><span class="glyphicon glyphicon-heart"></span> {{ 'ELIMINAR' | translate }}</a>
</p>
<p>
Link: {{ gif.url }}
</p>
</div>
</div>
</div>
<footer>
<p>© GIFWallet 2014</p>
</footer>
</div>
app.js
var gifwalletApp = angular.module('gifwalletApp', ['ui.bootstrap','pascalprecht.translate']);
gifwalletApp.config(function($translateProvider) {
$translateProvider.translations('en', {
FAVORITO: 'Favorite',
ELIMINAR: 'Delete'
})
.translations('es', {
FAVORITO: 'Favorito',
ELIMINAR: 'Eliminar'
});
$translateProvider.determinePreferredLanguage();
});
gifwalletApp.controller('TranslateController', function($translate, $scope) {
$scope.changeLanguage = function (langKey) {
$translate.use(langKey);
};
});
gifwalletApp.controller('gifListController', ['$rootScope','$scope','Storage','$http',
function($rootScope,$scope,Storage,$http){
$scope.giflist = Storage.list();
$rootScope.$on('reloadList', function(event, data){
$scope.giflist = Storage.list();
});
}]);
gifwalletApp.controller('MenuController', ['$rootScope','$scope', 'Storage','$modal',
function($rootScope,$scope, Storage, $modal) {
$scope.add = function() {
$modal.open({
templateUrl: 'add_gif.html',
controller: function($scope, $modalInstance) {
$scope.Gif = {};
$scope.save = function() {
var image = {
'name': $scope.Gif.name,
'url': $scope.Gif.url,
'tags': [],
'favorite': false
};
Storage.save(image);
$rootScope.$broadcast('reloadList');
$modalInstance.dismiss('cancel');
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}
});
};
}
]);
gifwalletApp.service('Storage', ['$window', function($window) {
var images = [];
if (!$window.localStorage) {
alert('No tienes localStorage activado');
} else {
images = $window.localStorage.getItem('gifWallet');
}
this.save = function(image) {
if (images == null) {
images = [];
}
else {
images = angular.fromJson(images);
}
images.push(image);
imagesString = JSON.stringify(images);
$window.localStorage.setItem('gifWallet', imagesString);
}
this.get = function(key) {
}
this.remove = function(key) {
}
this.list = function() {
return angular.fromJson($window.localStorage.getItem('gifWallet'));
}
}]);
add_gif.html
<div class="modal-header">
<h3 class="modal-title">Agregar GIF</h3>
<p class="text-muted">Añade un gif favorito a tu wallet usando el nombre y la URL</p>
</div>
<div class="modal-body">
<form action="" role="form">
<div class="form-group">
<label for="name">Nombre</label>
<input type="text" id="name" ng-model="Gif.name" placeholder="Corgi bailarín" class="form-control">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="url" id="url" ng-model="Gif.url" placeholder="http://..." class="form-control">
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-link" ng-click="cancel()">Cancelar</button>
<button class="btn btn-primary" ng-click="save()">Agregar GIF</button>
</div>
You shouldn't be using the src attribute with Angular Expressions.
Use ngSrc - as described in the docs.
<img class="media-object" ng-src="{{ gif.url }}">
Edit:
In your modalpanel you'll need to make sure the form that is beeing submitted is valid
Moved here from comment:
The reason why it won't work without the http:// is probably because the input field for the URL is of type="url" and urls are not valid with http/https. So it actually is a different problem here. The form should be validated before adding an image. :)
When you call partials in Angular, it makes a cross domain request. Firefox allows it, Chrome and others don't.
So, you have to launch a local web server to make it run on all browsers (Apache, with Xampp / Mamp, whatever).
Your script only runs on firefox because firefox allow cross origin requests (AJAX requests)
and chrome will not allow cross origin request because of security policies.
So in order to run your script in chrome You have to disable web security in chrome
To disable web-securities in chrome:
kill the chrome process
press "ctrl+R" to open run menu
type "chrome --disable-web-security" without quotes and press enter
then you will be able to run your script
Please let me know If you have any issues with other browsers?

Failed to load resource: the server responded with a status of 404 (Not Found) angular js + ionic

This is the error im having from Google Devt Tools. Anyone knows the problem? I tried to change in many times including the file structure and the stateProvider (no controllers for that) in app.js file but it does not seem to be the issue. (script is included in app.js with correct file name and directory)
In addition, my logout and submitPost buttons arent working as well.
newpost.html
<div class="modal slide-in-up" ng-controller="NavCtrl">
<!-- Modal header bar -->
<header class="bar bar-header bar-secondary">
<button class="button button-clear button-primary" ng-click="close()">Cancel</button>
<h1 class="title">New Shout</h1>
<button class="button button-positive" ng-click="submitPost()">Done</button>
</header>
<!-- Modal content area -->
<ion-content class="padding has-header">
<form class ng-submit="submitPost()" ng-show="signedIn()">
<div class="form-group">
<input type="text" class="form-control" placeholder="Title" ng-model="post.title">
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Link" ng-model="post.url">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</ion-content>
</div>
controller.js file
app.controller('NavCtrl', function ($scope, $firebase, $location, Post, Auth, $ionicModal) {
$scope.post = {url: 'http://', title: ''};
// Create and load the Modal
$ionicModal.fromTemplateUrl('newpost.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope,
animation: 'slide-in-up'
});
// Open our new task modal
$scope.submitPost = function () {
Post.create($scope.post).then(function (postId) {
$scope.post = {url: 'http://', title: ''};
$location.path('/posts/' + postId);
$scope.taskModal.show();
});
};
$scope.close = function() {
$scope.taskModal.hide();
};
$scope.logout = function () {
Auth.logout();
};
});
List of items page, post.html
<ion-header-bar class="bar-positive" ng-controller="NavCtrl">
<button class="button button-clear" ng-click="submitPost()">New</button>
<h1 class="title"><b><a class="navbar-brand" href="#/posts">MyApp</a></b></h1>
<button class="button button-clear" ng-click="logout()">Logout</button>
</ion-header-bar>
Change <base href="/"> to <base href="./"> from index.html
404 literally means that file was not found. It's simple as that. Check if the URL is right, and there are no rediretions being done(use fiddler). Perhaps the protocol should be https:// istead of http://? Perhaps you need "www" in url?
Click the url given in Chrome and see if the file exists.
Not sure if anyone is interested, but Experienced a similar problem when trying to upload to firebase storage here is how i resolved it.
The Error screenshot where upload fails with 503 and then 400 after 75% progress
The code segment I use for Upload is
//Event: data.Event,
// Date: data.Date,
// Time: data.Time
var data = getData();
data.filename=uploadfile.name;
var metadata = {
customMetadata: {
data
}
}
var storageRef = firebase.storage().ref().child("features");
console.log("Filenames to upload :" + uploadfile.name);
var fileRef = storageRef.child(uploadfile.name);
var uploadTask = fileRef.put(uploadfile,metadata);
The Problem was with custom meta data, once I changed it to like this,
var metadata = {
customMetadata: {
Event: data.Event,
Date: data.Date,
Time: data.Time
}
}
the upload started working. So, if there is an error in setting custom meta data, firebase errors out and possible does not provide that as a reason.
Screenshot of working here
successful upload once the custom meta data is corrected

Categories

Resources