data is lost after page refresh from local storage - javascript

i am storing user info into local storage, but every time i reload the page data is lost. not getting the exact solution. Here is my js code. i am getting value for user object from html in this format
{"fname":"A","lname":"B","age":"12","email":"a#b.com","class":"6","password":"1234"}
here is my js code
var app = angular.module("myApp",["ngStorage"]);
app.controller("myCtrl", function($scope,$localStorage,
$sessionStorage) {
var usersinfo= [];
$scope.submit = function() {
usersinfo.push($scope.user);
localStorage.setItem("usersinfo", JSON.stringify(usersinfo));
console.log(usersinfo);
};
});

You are importing $localStorage and using localStorage.
See documentation for read/write syntax.

The following example works fine when executed separately in an HTML file (Dont expect it to load localStorage in StackOverflow execution environment)
var user = {
"fname": "A",
"lname": "B",
"age": "12",
"email": "a#b.com",
"class": "6",
"password": "1234"
};
var app = angular.module("app", []);
app.controller("MyController", function($scope) {
console.log('Loaded');
$scope.usersinfo = [];
$scope.show = function() {
$scope.usersinfo = JSON.parse(localStorage.getItem('usersinfo'));
console.log($scope.usersinfo)
};
$scope.submit = function() {
$scope.usersinfo.push(user);
localStorage.setItem("usersinfo", JSON.stringify($scope.usersinfo));
console.log($scope.usersinfo);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController">
<p>Hi</p>
<button type="button" ng-click="submit()">Submit</button>
<button type="button" ng-click="show()">Show</button>
<p>{{usersinfo}}</p>
</div>
</div>

Related

authentication with angular js / json

i tried to make login form with angular js
i have list of user in json file but i can't comapre with the input text from login form
User.json :
[{
"username": "user1",
"password": "pass1"
}, {
"username": "user2",
"password": "pass2"
}, {
"username": "user3",
"password": "pass3"
}, {
"username": "user4",
"password": "pass4"
}]
script.js
var app1 = angular.module('app1', []);
var app2 = angular.module('app2', []);
var app = angular.module('app', ['app1', 'app2']);
app1.controller('jsonCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(res) {
$scope.users = res.data;
});
});
app2.controller('formCtrl', function($scope) {
$scope.login = function() {
if ($scope.username == 'test' && $scope.password == 'test') {
alert('valid username/password ' + $scope.username);
alert('user from json ' + $scope.users);
} else {
alert('invalid username/password ' + $scope.username);
}
};
});
index.html
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
<body ng-app="app">
<div ng-controller="formCtrl">
<form name="form">
First Name:<br>
<input type="text" ng-model="username"><br>
Last Name:<br>
<input type="text" ng-model="password">
<br><br>
<button ng-click="login()">LOGIN</button>
</form>
</div>
<div ng-controller="jsonCtrl">
<ul>
<li ng-repeat="user in users">
{{user.username}} / {{user.password}}
</li>
</ul>
</div>
</body>
</html>
the problem is replace if ($scope.username == 'test' && $scope.password == 'test') with anything compare with json
this my code : Plunker
You were using two different scopes across application. I moved all your markup under the same controller, so that is more simple manage the bindings.
Take a look at this plnkr
var app = angular.module('app', []);
app.controller('formCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(res) {
$scope.users = res.data;
});
$scope.login = function() {
var u = $scope.users.filter((item) => {
return item.username == $scope.username;
});
if (u[0] && u[0].password == $scope.password) {
alert('correct');
} else {
alert('wr0ng');
}
};
});
<div>
<form name="form">
First Name:
<br>
<input type="text" ng-model="username">
<br> Last Name:
<br>
<input type="text" ng-model="password">
<br>
<br>
<button ng-click="login()">LOGIN</button>
</form>
</div>
<div>
<ul>
<li ng-repeat="user in users">
{{user.username}} / {{user.password}}
</li>
</ul>
</div>
First of all, you should not authenticate user using clear text like that. Your server should do it with hashing table without knowing what is the real password.
Http.get is not synchronous which means that your application will continue its path without waiting for your data. In your plunker your formCtrl doesnt have access to jsonCtrl scope.
You should load your data in a service because it is initialised only once compared to the controller who are initialised everytime you load the page.
Finally you should start by looking at ui.router resolve, it allow you to load your data to your service before the page is displayed which will allow you to compare later.

div in ng-repeat is not getting updated?

I am getting a response from http get request and Iam using the response to iterate in the data
<div id="container" ng-app="myApp" ng-controller="myctrl">
<div ng-repeat="profile in profiles">
<p>{{profile.username}}</p>
</div>
</div>
This is for adding one profile on click
<input ng-click="addProfile()" type="button" value="add Profile" />
Here is my get request in the controller
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope, $http) {
$scope.profiles = [];
$http.get("test1.json")
.then(function(response) {
$scope.profiles = response.data.profiles; //Response is provided below
});
$scope.addProfile = function(){
$http.get('test2.json')
.then(function(response) {
alert("af");
$scope.items = response.data.profiles; //Response is provided below
$scope.profiles.push($scope.items);
console.log($scope.profiles); //gives the update Array
});
});
});
response of my get request of test1.json
{
"Id": "44442232",
"profiles": [
{
"type": "Friend",
"username": "Username 1",
},
{
"type": "Student ",
"username": "Username 2",
}
]
}
response of my get request of test2.json
{
"Id": "44442232",
"profiles": [
{
"type": "Friend",
"username": "Username 4",
},
{
"type": "Student ",
"username": "Username 5"
}
]
}
I have tried console.log after updating in the array.The array is updated but the div in ng-repeat is not getting updated?
Please close your JSON calling request by putting ')' at the end. There is no error apart from this and the same code works for me fine.
// Code goes here
var myApp = angular.module("myApp", []);
myApp.controller("myctrl", function($scope, $http) {
$http.get('test1.json')
.then(function(response) {
$scope.profiles = response.data.profiles; //Response is provided below
});
$scope.addProfile = function(){
$http.get('test2.json')
.then(function(response) {
$scope.items = response.data.profiles; //Response is provided below
angular.forEach($scope.items, function(value) {
$scope.profiles.push(value);
});
console.log($scope.profiles);
});
};
});
Please find this updated js code and check. Once it is fixed let me know. happy coding :)
First of all I don't think you need $scope.$apply() to trigger the digest cycle. You are in angular context.
Second, you are missing a ')' when you are calling .then(). You currently have '.then(function(){};'
Third, your response object should not have a comma after the username property if that property is the last one in the object.
Also do you have a silent fail, or it is an error in the console, and the processed html for the ng-repeat is blank or you get the angular interpolation syntax {{profile.username}}?

Why AngularJS $scope is not working correctly?

I'm new in AngularJS, I want to create an array and post it to server by register function, here's Controller code:
root.controller('mainController', function($scope) {
$scope.lineItems = [];
$scope.addItem = function (id) {
$scope.lineItems.push(id);
console.log($scope.lineItems);
// gives me right data -> Array [ "1", "2", "3", "4", "1" ]
};
$scope.register = function () {
// post data to server
console.log($scope.lineItems);
// gives me an empty array -> Array [ ]
};
});
Here's HTML code and directives:
<div class="container" ng-controller="mainController">
<a ng-click="register()"></a>
<div ng-repeat="product in products">
<a class="btn" ng-click="addItem(product.id)">Add</a>
</div>
</div>
The problem occurs when i want to call register function, it gives me an empty array instead of array elements while it's not gonna happen in addItem function.
This is your code and work correctly.
var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
$scope.products = [{id:1},{id:2},{id:3},{id:4}];
$scope.lineItems = [];
$scope.addItem = function (id) {
$scope.lineItems.push(id);
console.log($scope.lineItems);
// gives me right data
};
$scope.register = function () {
// post data to server
console.log($scope.lineItems);
// gives me an empty array
};
});
<div ng-app="testApp" ng-controller="testCtrl">
<a ng-click="register()">Register</a>
<div ng-repeat="product in products">
<a class="btn" ng-click="addItem(product.id)">Add : {{product.id}}</a>
</div>
</div>

How do you pass variables from an Angular controller to a html <script></script>?

I have variables in my angular controller and I'd like to take the data in the variable and put in a script tag in my html but I have no clue how to execute this. I'm doing this because I want to take a picture and put it into my LinkedIn post with the share button. Based on the docs here, it seems pretty straight forward if I can just get the data from my controller into their script tags.
For example:
controller.js
.controller('PostCtrl', function ($scope, $http, $stateParams) {
$scope.test = "something";
$scope.hope = 5
$scope.array = [things];
}
html
<script>
var payload = {
"comment": $scope.test "content": {
"title": $scope.hope,
"someArray": $scope.array,
"submitted-url": window.location.href
}
};
</script>
//////////////////////////
Thanks for the copious comments. Here is what I'm trying in more detail with LinkedIn:
<script type="IN/Share" data-url={{webAddress}} data-counter="right">
$.get( "https://public-api.wordpress.com/rest/v1.1/sites", function( response ) {
var post = _.first(_.filter(response.posts, function(n){return n.title.replace(/ /g,"-").replace(/[:]/g, "").toLowerCase() === $stateParams.id}));
var post1 = _.assign(post, {category: _.first(_.keys(post.categories)), pic: _.first(_.values(post.attachments)).URL, credit: _.first(_.values(post.attachments)).caption, linkCredit: _.first(_.values(post.attachments)).alt, fullStory: post.content.replace(/<(?!\s*\/?\s*p\b)[^>]*>/gi,'')});
**var image = post1.pic;**
**var title = post1.title;**
**var webAddress = window.location.href;**
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
function shareContent(title, image, webAddress) {
var payload = {
"content": {
"title": title,
"submitted-image-url": image,
"submitted-url": webAddress
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
});
</script>
I still think something is going wrong. But what? Am I using the http correctly as I've only done it using Angular thus far.
See the snippet just below how to access Angular Scope outside angular :)
EDIT (Afer reading your updated question)
You'll better transcode all your LinkedIn scripts to angular way as kicken suggest you :) :
less spagetti code
less maintenance
more time to watch lol cats on YT !
If you still want to do that way :) ==>
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.test = 'toto';
$scope.hope = 'My Title';
$scope.array = ['A', 'B', 'C'];
$scope.payload = {};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var myFunction = function() {
var e = document.getElementById('app');
var $scope = angular.element(e).scope();
console.log($scope.payload);
$scope.payload = {
"comment": $scope.test,
"content": {
"title": $scope.hope,
"someArray": $scope.array,
"submitted-url": window.location.href
}
};
$scope.$apply();
};
</script>
<body ng-app="app" ng-controller="MainCtrl" id="app">
<p>Hello {{payload}}!</p>
<button onclick="javascript:myFunction()">Click me</button>
</body>
Rather than try and pass data from Angular into a generic <script> tag, what you need to do is move the LinkedIn code into Angular.
A quick glance at the JavascriptSDK documentation suggests that this is the key code for making the linked in request:
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
What you can do then is place that code into your angular code at whatever point you need it. You mention the data for your payload comes from a $http request so you would likely want this into your $http success handler.
$http({url:'/whatever'}).then(function(response){
var payload = { /* Generate payload */ };
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
function onSuccess(){ /* LinkedIn success */ }
function onError(){ /* LinkedIn error */ }
});
As others have suggested, moving all of your javascript code into your controller would be the best solution if possible. To do that, your controller would look something like this:
.controller('PostCtrl', function ($scope, $http, $stateParams) {
$scope.test = "something";
$scope.hope = 5
$scope.array = [things];
$scope.sendData = function () {
var data = $.param({
"comment": $scope.test,
"content": {
"title": $scope.hope,
"someArray": $scope.array,
"submitted-url": window.location.href
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$http.post('https://api.linkedin.com/v1/people/~/shares?format=json', data, config)
.success(function (data, status, headers, config) {
//it worked
})
.error(function (data, status, header, config) {
//there was an error
});
};
}
Then, in your html, you would put ng-submit="sendData()" on the form you use to share. If the share stuff isn't in a form, you could then just do ng-click="sendData()".

AngularJS - $http POST with Rails 3.2.3

I'm building a simple Contact Management app with Crud using AngularJS 1.0.0rc8.
Getting a list of currently existing contacts is no problem, but while attempting to save a new Contact to the server, a new row is created - complete with the correct id, created_at, and updated_at values - but the rest of the models data is ignored.
Here is a screenshot to show what I mean:
As you can see, numbers 4 and 5 were given the Id's but first_name, last_name, and phone_num were not saved to the database.
I am using a $scope.addContact function within the Controller that deals with the object.
Here is the entire code for the Contact List Controller:
'use strict';
function ContactListCtrl($scope, $http) {
$http.get('/contacts').success(function(data) {
$scope.contacts = data;
});
$scope.addContact = function(data) {
$http.post('/contacts/', data).success(function(data) {
console.log(data);
data.first_name = $("#new_contact_first_name").val();
data.last_name = $("#new_contact_last_name").val();
});
this.newFirstName = '';
this.newLastName = '';
};
};
After clicking 'Save' on the new-contact.html partial, the Object is logged to the Console, if I inspect its contents, than sure enough the values are collected - notice Jimi Hendrix is there:
Here is the form as it appears in the new-contact.html template:
<form id="contact_form" ng-submit="addContact()">
<input type="text" id="new_contact_first_name" name="newContactFirstName" ng-model="newFirstName" placeholder="First Name"></br>
<input type="text" id="new_contact_last_name" name="newContactLastName" ng-model="newLastName" placeholder="Last Name"></br>
<input type="button" id="contact_submit_btn" value="Add Contact" class="btn btn-primary">
</form>
The addContact() function is fired after the form is submitted with JQuery:
$(document).ready(function(){
$("#contact_submit_btn").click(function(){
$("#contact_form").submit();
});
});
(Something tells me that I may not be using the ng-model attributes correctly.)
Any ideas on where I am going wrong with this? Or ideas on how I can better go about implementing this design?
Thanks.
UPDATE BELOW:
Here is my entire updated controller code - with help from Sathish:
// contacts controllers
'use strict';
function ContactListCtrl($scope, $http, Contacts) {
$scope.contacts = Contacts.index();
$scope.addContact = function() {
var newContact = {
first_name: $scope.newContactFirstName,
last_name: $scope.newContactLastName
};
var nc = new Contacts({ contact: newContact });
nc.$create(function() {
$scope.contacts.push(nc);
// now that the contact is saved, clear the form data
$scope.newContactFirstName = "";
$scope.newContactLastName = "";
})
}
};
ContactListCtrl.$inject = ['$scope', '$http', 'Contacts'];
function ContactDetailCtrl($scope, $routeParams, Contacts) {
$scope.contact = Contacts.get( {contact_id: $routeParams.contact_id} );
}
ContactDetailCtrl.$inject = ['$scope', '$routeParams', 'Contacts'];
I am now receiving the error: Unknown Provider for Contacts. Here is a screenshot of the error
Ok, I managed to fix that error by providing a ngResource to the main App file. Here's what it looks like:
// main app javascript file
'use strict';
angular.module('contactapp', ['ngResource']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/contacts', {template: 'assets/app/partials/contact-list.html', controller: ContactListCtrl}).
when('/contacts/new', {template: 'assets/app/partials/new-contact.html', controller: ContactListCtrl}).
when('/contacts/:contact_id', {template: 'assets/app/partials/contact-detail.html', controller: ContactDetailCtrl}).
otherwise({redirectTo: '/contacts'});
}]);
I am receiving a new error: WARNING: Can't verify CSRF token authenticity
Alright, managed to fix that problem too by adding a callback to the API controller:
Rails shows "WARNING: Can't verify CSRF token authenticity" from a RestKit POST
Now I am back to the original problem. When the create method is called, a new row is saved to the database, but the models data is not.
Awesome... finally got this thing working.
The problem was the $scope.addContact function. It was using the 'name' of the input instead of the ng-model binding called 'newFirstName' and 'newLastName' that resides in the template.
Here's what the updated function looks like:
$scope.addContact = function() {
var newContact = {
first_name: $scope.newFirstName,
last_name: $scope.newLastName
};
var nc = new Contacts({ contact: newContact });
nc.$create(function() {
$scope.contacts.push(nc);
// now that the contact is saved, clear the form data
$scope.newFirstName = "";
$scope.newLastName = "";
})
}
This can be better implemented using a Contacts service. Please define a Contacts service in app/assets/javascripts/services.js.erb as shown below:
var servicesModule = angular.module('<your app name>',
[<list of modules needed by this app>]);
servicesModule.factory('Contacts', function($resource) {
var ContactsService = $resource('/contacts/:contact_id', {}, {
'create': { method: 'POST' },
'index': { method: 'GET', isArray: true },
'update': { method: 'PUT' },
'destroy': { method: 'DELETE' }
});
return ContactsService;
});
Change the addContact method in the controller as shown below:
function ContactListCtrl($scope, $http, Contacts) {
...
...
...
$scope.addContact = function () {
var newContact = {
first_name: $scope.newContactFirstName,
last_name: $scope.newContactLastName
};
var nc = new Contacts({ contact: newContact });
nc.$create(function() {
$scope.contacts.push(nc);
// now that the contact is saved, clear the form data.
$scope.newContactFirstName = "";
$scope.newContactLastName = "";
});
};
...
...
...
}
ContactListCtrl.$inject = ['$scope', '$http', 'Contacts'];
In addition to this, you can simplify the $http.get(...) part also. You can use Contacts.index();
Note:
If you gave ng-app="MyAppName" then please replace <your app name> with MyAppName.
<list of modules needed by this app> needs to the replaced by a comma-separated list of strings representing any modules needed by your application.
Check the attr_accessible on your model. With new 3.2.3 rails all model attributes became protected from mass-assignment by default.

Categories

Resources